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

后端 未结 1 495
梦谈多话
梦谈多话 2020-12-28 18:50

[Documentation about collection] When embedding forms (collection type) is possible to specify validation groups for each item, based on the current item? It seems not worki

相关标签:
1条回答
  • 2020-12-28 19:06

    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,
        ));
      }
    }
    
    0 讨论(0)
提交回复
热议问题