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

爷,独闯天下 提交于 2020-01-29 13:23:29

问题


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.


回答1:


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

http://symfony.com/doc/current/book/forms.html#groups-based-on-the-submitted-data

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';
            }
        ]);
}



回答2:


Just remove the child fields prior to validation if the parent's checkbox is set to false.

Read more in the cookbook article How to Dynamically Modify Forms Using Form Events.

Subscribe to form events FormEvents::POST_SET_DATA and remove the field in your subscriber.

The section Adding an Event Subscriber to a Fom class covers this topic.


You can aswell introduce different validation groups for your form.

Just apply another validation group ( not containing the chield fields ) if the parent's checkbox is set to false.



来源:https://stackoverflow.com/questions/17104501/skip-validation-if-sibling-checkbox-field-contains-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!