Skip to content

Commit 155b47a

Browse files
committed
[Validator] Added grouped constraints in Collection reference
1 parent 2a475ba commit 155b47a

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

reference/constraints/Collection.rst

+35-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ following:
9494
profileData:
9595
- Collection:
9696
fields:
97-
personal_email:
97+
personal_email:
9898
- Email: ~
9999
short_bio:
100100
- NotBlank: ~
@@ -287,6 +287,40 @@ However, if the ``personal_email`` field does not exist in the array,
287287
the ``NotBlank`` constraint will still be applied (since it is wrapped in
288288
``Required``) and you will receive a constraint violation.
289289

290+
When you define groups in nested constraints they are automatically added to
291+
the ``Collection`` constraint itself so it can be traversed for all nested
292+
groups. Take the following example::
293+
294+
use Symfony\Component\Validator\Constraints as Assert;
295+
296+
$constraint = new Assert\Collection([
297+
'fields' => [
298+
'name' => new Assert\NotBlank(['groups' => 'basic']),
299+
'email' => new Assert\NotBlank(['groups' => 'contact']),
300+
],
301+
]);
302+
303+
This will result in the following configuration::
304+
305+
$constraint = new Assert\Collection([
306+
'fields' => [
307+
'name' => new Assert\Required([
308+
'constraints' => new Assert\NotBlank(['groups' => 'basic']),
309+
'groups' => ['basic', 'strict'],
310+
]),
311+
'email' => new Assert\Required([
312+
"constraints" => new Assert\NotBlank(['groups' => 'contact']),
313+
'groups' => ['basic', 'strict'],
314+
]),
315+
],
316+
'groups' => ['basic', 'strict'],
317+
]);
318+
319+
The default ``allowMissingFields`` option requires the fields in all groups.
320+
So when validating in ``contact`` group, ``$name`` can be empty but the key is
321+
still required. If this is not the intended behavior, use the ``Optional``
322+
constraint explicitly instead of ``Required``.
323+
290324
Options
291325
-------
292326

validation/raw_values.rst

+7
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,10 @@ The ``validate()`` method returns a :class:`Symfony\\Component\\Validator\\Const
105105
object, which acts just like an array of errors. Each error in the collection
106106
is a :class:`Symfony\\Component\\Validator\\ConstraintViolation` object,
107107
which holds the error message on its ``getMessage()`` method.
108+
109+
.. note::
110+
111+
When using groups with the
112+
:doc:`Collection</reference/constraints/Collection>` constraint, be sure to
113+
use the ``Optional`` constraint when appropriate as explained in its
114+
reference documentation.

0 commit comments

Comments
 (0)