I have some complex form, with several subforms, and I want to be able to validate each subform separately depending on radio button choosen in main form. I wanted to achieve this with validation groups.
Note: I have no data_class
model, I work with arrays.
Here is my form simplified:
class MyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('xxx', 'text', array(
'constraints' => array(
new Constraints\NotBlank(),
),
'validation_groups' => array(
'xxx',
)
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => function(FormInterface $form) {
return array('xxx');
},
));
}
}
The problem is that validation for this field is not triggered.
When this works, I can easily change setDefaultOptions
to validate desired group depending on submitted data:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => function(FormInterface $form) {
$data = $form->getData();
return array($data['type']);
},
));
}
Any idea?
You have to pass the validation group name to the constraint, not in the form itself. By assigning group name to a form you specify which constraints to use in validation.
Replace
$builder->add('xxx', 'text', array(
'constraints' => array(
new Constraints\NotBlank(),
),
'validation_groups' => array(
'xxx',
)
))
;
With
$builder->add('xxx', 'text', array(
'constraints' => array(
new Constraints\NotBlank(array(
'groups' => 'xxx'
)),
),
))
;
By default, constraints have the 'Default' (capitalized) group and forms use this group to validate if none specified. If you want the other constraints with no explicit group to validate, along with specified group pass the 'Default' one.
$resolver->setDefaults(array(
'validation_groups' => function(FormInterface $form) {
$data = $form->getData();
return array($data['type'], 'Default');
},
));
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