umpirsky
umpirsky

Reputation: 10024

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?

Upvotes: 5

Views: 5096

Answers (1)

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10146

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

Upvotes: 13

Related Questions