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

孤人 提交于 2019-11-30 03:30:00

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