diff --git a/reference/constraints/Collection.rst b/reference/constraints/Collection.rst index 2f3dfd52035..c60679aa90b 100644 --- a/reference/constraints/Collection.rst +++ b/reference/constraints/Collection.rst @@ -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 ------- diff --git a/validation/raw_values.rst b/validation/raw_values.rst index 8cee65108b8..2014d37644b 100644 --- a/validation/raw_values.rst +++ b/validation/raw_values.rst @@ -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` constraint, be sure to + use the ``Optional`` constraint when appropriate as explained in its + reference documentation.