Specify different validation groups for each item of a collection in Symfony 2? Specify different validation groups for each item of a collection in Symfony 2? symfony symfony

Specify different validation groups for each item of a collection in Symfony 2?


The complete code I used to test my answer is on https://github.com/guilro/SymfonyTests/tree/SO21276662.

Valid constraint force Validator to validate embed object, and AFAIK the API provides no way to set validation group.

But at a higher level, we can ask Form component to cascade ValidationListener to all embed forms, and use the Form component API to set validation group.

We must use :

  • 'cascade_validation' => true option in the FormBuilder, at all levels. It is set to false by default.
  • a callback in TagType settings to set validation group. (You were on the right track.)
  • 'error_bubbling' => false, as it is true by default in collections

and we're done, we can display the form with all errors next to corresponding fields.

in TaskType.php :

class TaskType extends AbstractType{  public function buildForm(FormBuilderInterface $builder, array $options)  {    $builder        ->add('name')        ->add('tags', 'collection', array(            'type' => 'tag',            'error_bubbling' => false,            'allow_add' => true,            'by_reference' => false,            'cascade_validation' => true        ))    ;  }  public function setDefaultOptions(OptionsResolverInterface $resolver)  {    $resolver->setDefaults(array(        'data_class' => 'Acme\TaskBundle\Entity\Task',        'cascade_validation' => true    ));  }}

in TagType.php :

class TagType extends AbstractType{  public function buildForm(FormBuilderInterface $builder, array $options)  {    $builder        ->add('name')        ->add('description', 'text', array('required' => false));  }  public function setDefaultOptions(OptionsResolverInterface $resolver)  {    $resolver->setDefaults(array(        'data_class' => 'Acme\TaskBundle\Entity\Tag',        'validation_groups' => function(FormInterface $form) {            if ($form->getData() !== null && null !== $form->getData()->getId())            {                return array('Edit');            }            return array('Default');        },        'error_bubbling' => false,    ));  }}