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

后端 未结 2 822
梦如初夏
梦如初夏 2021-01-13 07:00

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 l

相关标签:
2条回答
  • 2021-01-13 07:24

    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';
                }
            ]);
    }
    
    0 讨论(0)
  • 2021-01-13 07:34

    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.

    0 讨论(0)
提交回复
热议问题