将验证组设置为symfony中的嵌入式表单2

前端之家收集整理的这篇文章主要介绍了将验证组设置为symfony中的嵌入式表单2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在嵌入式表单中设置验证组?
我有两个实体A和B,并为每个实体(FormA,FormB)
我在FormB中嵌入FormA
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
        ));
    }
}

如何从FormB设置FormA的验证组?

解决方法

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

还可以在FormB-> setDefaultOptions中定义验证组.它将验证组应用于所有子表单.

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

要根据底层数据使用它,您可以将该代码放在事件侦听器上:

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',array('validation_groups' => array('yourValidationGroup')));
                } else {
                    $form->add('A',array());
                }
            }
    );
}
原文链接:https://www.f2er.com/html/230350.html

猜你在找的HTML相关文章