Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip validation if sibling (checkbox) field contains 'false'

I have a form containing a checkbox and a "value field". The value field could be anything, a text box, a compound field, a collection - anything.

The form could look like this, for example:

field_1_label    enabled    [x]
                 value      [________]

field_2_label    enabled    [x]
                 value      sub_field_1    [________]
                            sub_field_2    [________]

field_3_label    enabled    [x]
                 value      [________]

When the "enabled" field contains true, everything works fine already. When the "enabled" field contains false, I would like to disable validation on the value field and it's child fields.

So when "enabled" is un-checked, I will effectively ignore the field. I will still display it in the form, but I won't store the data and I certainly don't want it validated.

Does anybody have suggestions for how I might do this? Specifically, I'm having problems getting the validation system to ignore the value field and any potential child fields.

like image 233
ledneb Avatar asked Jun 14 '13 08:06

ledneb


1 Answers

In Symfony 2.3 you can use false in validation_groups to have no constraints applied:

https://symfony.com/doc/current/form/button_based_validation.html

So for example, on the field containing the checkbox and value field:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver
        ->setDefaults([
            'validation_groups' => function(FormInterface $form) {
                // If the form is disabled, don't use any constraints
                if ($form->get('enabled_checkbox')->getData() == false) {
                    return false;
                }
                
                // Otherwise, use the default validation group
                return 'Default';
            }
        ]);
}
like image 90
user997224 Avatar answered Sep 18 '22 10:09

user997224