Reputation: 7135
I have an embedded form (for Address
) which has its own validations for various properties. I embed this form in a parent form (for Person
), and I have a checkbox on the parent form that says something like "Person has an address?"
When the checkbox is left unchecked, I want to disable all the validation for the embedded Address
form. Or, better yet, if I can just remove the embedded form from being submitted completely that would be OK too.
I looked at using validation groups, but the use case doesn't match my own.
Upvotes: 4
Views: 1829
Reputation: 7135
OK, figured this out. When adding the AddressType
embedded form in my form builder, I just pass in the option for validation groups like so:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
$form->add('address', new AddressType(), array(
'label' => 'Address',
'validation_groups' => function (FormInterface $form) {
if ($form->getParent()->get('toggleAddress')->getData() === false) {
return array();
}
return array('Default');
}
));
});
Within the validation group function, a check is made to see if the toggle to enable Address is off. If so, return a blank array, with removes all validation groups, including the "Default" one.
Upvotes: 2
Reputation: 5864
You try to fix your issue with validation group which will not cover your use case (it can but it will be tricky because en empty Address
object will be linked to your Person
object).
Basically, you embed your Address
form everytime whereas it should only be embed when the checkbox is checked. IMHO, you should rely on dynamic form as explained here.
With this solution, you will need extra JS code in order to update you form when you click the checkbox in order to update the whole form accordingly. Then, there will be no issue about validation because the Address object will only be created when the form is embed.
Additionally (just for information), you can add/edit validation groups according to the submitted data as explained here.
Hope my answer is helpfull!
Upvotes: 0