如何在嵌入式表单中设置验证组?
我有两个实体A和B,并为每个实体(FormA,FormB)
我在FormB中嵌入FormA
我有两个实体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()); } } ); }