Skip to content

[Validator] Added grouped constraints in Collection reference #13492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions reference/constraints/Collection.rst
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,40 @@ However, if the ``personal_email`` field does not exist in the array,
the ``NotBlank`` constraint will still be applied (since it is wrapped in
``Required``) and you will receive a constraint violation.

When you define groups in nested constraints they are automatically added to
the ``Collection`` constraint itself so it can be traversed for all nested
groups. Take the following example::

use Symfony\Component\Validator\Constraints as Assert;

$constraint = new Assert\Collection([
'fields' => [
'name' => new Assert\NotBlank(['groups' => 'basic']),
'email' => new Assert\NotBlank(['groups' => 'contact']),
],
]);

This will result in the following configuration::

$constraint = new Assert\Collection([
'fields' => [
'name' => new Assert\Required([
'constraints' => new Assert\NotBlank(['groups' => 'basic']),
'groups' => ['basic', 'strict'],
]),
'email' => new Assert\Required([
"constraints" => new Assert\NotBlank(['groups' => 'contact']),
'groups' => ['basic', 'strict'],
]),
],
'groups' => ['basic', 'strict'],
]);

The default ``allowMissingFields`` option requires the fields in all groups.
So when validating in ``contact`` group, ``$name`` can be empty but the key is
still required. If this is not the intended behavior, use the ``Optional``
constraint explicitly instead of ``Required``.

Options
-------

Expand Down
7 changes: 7 additions & 0 deletions validation/raw_values.rst
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,10 @@ The ``validate()`` method returns a :class:`Symfony\\Component\\Validator\\Const
object, which acts like an array of errors. Each error in the collection
is a :class:`Symfony\\Component\\Validator\\ConstraintViolation` object,
which holds the error message on its ``getMessage()`` method.

.. note::

When using groups with the
:doc:`Collection</reference/constraints/Collection>` constraint, be sure to
use the ``Optional`` constraint when appropriate as explained in its
reference documentation.