Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set validation group to embedded forms in symfony 2

how to set validation group in embedded forms ? I have two entities A and B and form for each entities (FormA, FormB) I am embedding form FormA in FormB

class FormB extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('A', new FormA());
    }
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\TestBundle\Entity\B',
            'validation_groups'=>function(FormInterface $form) {
                // set validation group for FormA here
             },
            'cascade_validation'=>true
        ));
    }
}

How do I set validation group of FormA from FormB?

like image 801
sonam Avatar asked Sep 11 '13 11:09

sonam


2 Answers

It works for me

class FormB extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('A', new FormA(), array('validation_groups' => array('yourValidationGroup')));
    }
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\TestBundle\Entity\B',
            'cascade_validation'=>true
        ));
    }
}

Also defining the validation group in FormB->setDefaultOptions work. It apply the validation group to all subforms.

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\TestBundle\Entity\B',
            'cascade_validation'=>true,
            'validation_groups' => array('yourValidationGroup')
        ));
    }

To use that depending on underlying data you can put that code on a event listener:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->addEventListener(
            FormEvents::POST_SET_DATA,
            function(FormEvent $event) {
                $form=$event->getForm();
                /**
                 * @var ContactDetail $detail
                 */
                $entity=$form->getData();
                if($entity->getA()->isRequired()){
                    $form->add('A', new FormA(), array('validation_groups' => array('yourValidationGroup')));
                } else {
                    $form->add('A', new FormA(), array());
                }
            }
    );
}
like image 179
albert Avatar answered Nov 05 '22 04:11

albert


The property cascade_validation is deprecated in Symfony 2.8, and will be removed in Symfony 3.0. For use cascade_validation, you should use @Assert\Valid constraint.

class Profile
{
  /**
   * @var Address
   * 
   * @Assert\Valid()
   */
  private $address;
}

P.S. Attention: links provides for Symfony 2.8 version.

like image 41
ZhukV Avatar answered Nov 05 '22 03:11

ZhukV