New in Symfony 3.4: Groups support for the Valid constraint
Contributed by
Christian Flothmann
in #21111.
The Valid constraint enables validation on objects that are embedded as properties on the object being validated. This allows you to validate an object and all sub-objects associated with it. For example, validate the Address object embedded in an Author object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // src/AppBundle/Entity/Address.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Address
{
/** @Assert\NotBlank() */
protected $street;
/** @Assert\Length(max = 5) */
protected $zipCode;
}
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/** @Assert\NotBlank */
protected $firstName;
/** @Assert\NotBlank */
protected $lastName;
/** @Assert\Valid */
protected $address;
}
|
The main shortcoming of this constraint it that it doesn't support validation groups. In Symfony 3.4, we improved the Valid constraint to add support for groups:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // src/AppBundle/Entity/Address.php
// ...
class Address
{
/** @Assert\NotBlank(groups={"basic"}) */
protected $street;
/** @Assert\Length(max = 5) */
protected $zipCode;
}
// src/AppBundle/Entity/Author.php
// ...
class Author
{
/** @Assert\NotBlank */
protected $firstName;
/** @Assert\NotBlank */
protected $lastName;
/** @Assert\Valid(groups={"basic"}) */
protected $address;
}
|
In the previous example, the Valid
constraint only validates the properties
that belong to the basic
group in the Address
object, so it will only
validate the street
property and not the zipCode
property.
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
New in Symfony 3.4: Groups support for the Valid constraint symfony.com/blog/new-in-symfony-3-4-groups-support-for-the-valid-constraint
Tweet thisComments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Oskar Stark said on Sep 15, 2017 at 10:40 #1