如何在嵌入表单中设置验证组? 我有两个实体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的验证组?
答案 0 :(得分:8)
它对我有用
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());
}
}
);
}
答案 1 :(得分:1)
属性class Profile
{
/**
* @var Address
*
* @Assert\Valid()
*/
private $address;
}
为deprecated in Symfony 2.8,将在Symfony 3.0中删除。要使用filter-branch
,您应该使用@Assert\Valid
constraint。
git rm --cached
P.S。注意:链接提供Symfony 2.8版本。