Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 form validation groups based on submitted data

I have some complex form, with several subforms, and I want to be able to validate each subform separately depending on radio button choosen in main form. I wanted to achieve this with validation groups.

Note: I have no data_class model, I work with arrays.

Here is my form simplified:

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('xxx', 'text', array(
                'constraints' => array(
                    new Constraints\NotBlank(),
                ),
                'validation_groups' => array(
                    'xxx',
                )
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => function(FormInterface $form) {
                return array('xxx');
            },
        ));
    }
}

The problem is that validation for this field is not triggered.

When this works, I can easily change setDefaultOptions to validate desired group depending on submitted data:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function(FormInterface $form) {
            $data = $form->getData();

            return array($data['type']);
        },
    ));
}

Any idea?

like image 822
umpirsky Avatar asked Dec 16 '22 17:12

umpirsky


1 Answers

You have to pass the validation group name to the constraint, not in the form itself. By assigning group name to a form you specify which constraints to use in validation.

Replace

$builder->add('xxx', 'text', array(
        'constraints' => array(
            new Constraints\NotBlank(),
        ),
        'validation_groups' => array(
            'xxx',
        )
    ))
;

With

$builder->add('xxx', 'text', array(
        'constraints' => array(
            new Constraints\NotBlank(array(
                'groups' => 'xxx'
            )),
        ),
    ))
;

By default, constraints have the 'Default' (capitalized) group and forms use this group to validate if none specified. If you want the other constraints with no explicit group to validate, along with specified group pass the 'Default' one.

$resolver->setDefaults(array(
    'validation_groups' => function(FormInterface $form) {
        $data = $form->getData();

        return array($data['type'], 'Default');
    },
));
like image 103
Vadim Ashikhman Avatar answered Jan 15 '23 02:01

Vadim Ashikhman