0

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),
        ),
    ))
;

sources

Is there a way to assign them to a validation constraint ?

In my case, I have validation groups depending on submitted data

Thanks in advance for your suggestions

Żabojad
  • 2,946
  • 2
  • 32
  • 39

1 Answers1

3

OK, well the solution was pretty straighforward actually.

Looking at the Constraint 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...

Żabojad
  • 2,946
  • 2
  • 32
  • 39