Contributed by
Yevgeniy Zholkevskiy
in #26555.
In Symfony 4.3, the Validator component added a new constraint called
Unique
to validate that the elements of a collection are unique (none of
them is present more than once):
1 2 3 4 5 6 7 8 9 10 11 12 | // src/Entity/Person.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Person
{
/**
* @Assert\Unique(message="The {{ value }} email is repeated.")
*/
protected $contactEmails;
}
|
1 2 3 4 5 6 | # config/validator/validation.yaml
App\Entity\Person:
properties:
contactEmails:
- Unique:
message: 'The {{ value }} email is repeated.'
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="https://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="App\Entity\Person">
<property name="contactEmails">
<constraint name="Unique">
<option name="message">The {{ value }} email is repeated.</option>
</constraint>
</property>
</class>
</constraint-mapping>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // src/Entity/Person.php
namespace App\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
class Person
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('contactEmails', new Assert\Unique([
'message' => 'The {{ value }} email is repeated.',
]));
}
}
|
The new constraint can be applied to any property of type array or
\Traversable
and the comparison is strict, so different types are considered
different elements (e.g. '7'
(string) is different than 7
(integer)).
Symfony already provides some validators related to collections and uniqueness, so keep in mind that:
Collection
: applies different validation constraints for each collection
element.Unique
: validates that all the elements of a collection are unique.UniqueEntity
: validates that the given property value is unique among all
entities of the same type (e.g. the registration email is unique for all the
application users).What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...