7

I want to know how can I validate array of arrays in symfony. My validation rules are:

  1. User - NotBlank
  2. Date - Date and NotBlank
  3. Present - NotBlank

So far I have done this:

$validator = Validation::createValidator();

$constraint = new Assert\Collection(array(
        'user' => new Assert\NotBlank(),
        'date' => new Assert\Date(),
        'present' => new Assert\NotBlank()
));

$violations = $validator->validate($request->request->get('absences')[0], $constraint);

But the problem is that it only allows to validate single array eg.
$request->request->get('absences')[0].

Here is how the array looks like:

enter image description here

Martin
  • 1,259
  • 3
  • 17
  • 36
  • Possible duplicate of [Use a custom constraint/validator in symfony form type](https://stackoverflow.com/questions/35870980/use-a-custom-constraint-validator-in-symfony-form-type) – Mike Doe Nov 19 '18 at 12:11
  • Where do you see the duplicate? – Martin Nov 19 '18 at 12:31

1 Answers1

18

You have to put the Collection constraint inside All constraint:

When applied to an array (or Traversable object), this constraint allows you to apply a collection of constraints to each element of the array.

So, your code will probably look like this:

$constraint = new Assert\All(['constraints' => [
    new Assert\Collection([
        'user' => new Assert\NotBlank(),
        'date' => new Assert\Date(),
        'present' => new Assert\NotBlank()
    ])
]]);

Update: if you want to use annotations for this, it'll look something like this:

@Assert\All(
    constraints={
        @Assert\Collection(
            fields={
                "user"=@Assert\NotBlank(),
                "date"=@Assert\Date(),
                "present"=@Assert\NotBlank()
            }
        )
    }
)
xYundy
  • 83
  • 7
Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25