如何设置嵌入形式的验证组?
我有两个实体A和B,每个实体都有一个表单(FormA,FormB)
我将FormA嵌入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
));
}
}
如何设置来自FormB的FormA验证组?
最佳答案
这个对我有用
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
));
}
}
还可以在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', new FormA(), array('validation_groups' => array('yourValidationGroup')));
} else {
$form->add('A', new FormA(), array());
}
}
);
}