March 29, 2019 Javier Eguiluz

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):

Annotations 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 ; }

YAML 1 2 3 4 5 6 # config/validator/validation.yaml App\Entity\Person : properties : contactEmails : - Unique : message : 'The {{ value }} email is repeated.'

XML 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= "http://symfony.com/schema/dic/constraint-mapping" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://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>

PHP 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: