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?
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());
}
}
);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With