
Question:
I'd like to be able to add in a Form class additional validation constraints for a specific validation group. How could I do that ?
Since Symfony 2.1, adding a validation while building the form looks like this :
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\NotBlank;
$builder
->add('firstName', 'text', array(
'constraints' => new MinLength(3),
))
->add('lastName', 'text', array(
'constraints' => array(
new NotBlank(),
new MinLength(3),
),
))
;
<a href="http://symfony.com/blog/form-goodness-in-symfony-2-1" rel="nofollow">sources</a>
Is there a way to assign them to a validation constraint ?
In my case, I have <a href="http://symfony.com/doc/2.2/book/forms.html#groups-based-on-submitted-data" rel="nofollow">validation groups depending on submitted data</a>
Thanks in advance for your suggestions
Answer1:OK, well the solution was pretty straighforward actually.
Looking at the <a href="http://api.symfony.com/2.2/Symfony/Component/Validator/Constraint.html" rel="nofollow">Constraint</a> class, I noticed the exposed $groups property and addImplicitGroupName(string $group) method.
When you know that, you know all about it:
$cv1 = new NotBlank();
$cv1->groups = array('myGroup');
$cv2 = new NotNull();
$cv2->groups = array('myGroup');
$myCnstrs = array(
'constraints' => array(
$cv1,
$cv2,
)
);
$myOtherOptions = array(
...
);
$builder->add('myField', null, array_merge($myCnstrs,$myOtherOptions));
Sorry if I abused by posting a question and replying to it right after...