UniqueEntity

UniqueEntity

Validates that a particular field (or fields) in a Doctrine entity is (are) unique. This is commonly used, for example, to prevent a new user to register using an email address that already exists in the system.

See also

If you want to validate that all the elements of the collection are unique use the Unique constraint.

Note

In order to use this constraint, you should have installed the symfony/doctrine-bridge with Composer.

Applies toclass
Options
ClassSymfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity
ValidatorSymfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator

Basic Usage

Suppose you have a User entity that has an email field. You can use the UniqueEntity constraint to guarantee that the email field remains unique between all of the rows in your user table:

  • Annotations

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Doctrine\ORM\Mapping as ORM;
    4. // DON'T forget the following use statement!!!
    5. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    6. use Symfony\Component\Validator\Constraints as Assert;
    7. /**
    8. * @ORM\Entity
    9. * @UniqueEntity("email")
    10. */
    11. class User
    12. {
    13. /**
    14. * @ORM\Column(name="email", type="string", length=255, unique=true)
    15. * @Assert\Email
    16. */
    17. protected $email;
    18. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\User:
    3. constraints:
    4. - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: email
    5. properties:
    6. email:
    7. - Email: ~
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\User">
    7. <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
    8. <option name="fields">email</option>
    9. </constraint>
    10. <property name="email">
    11. <constraint name="Email"/>
    12. </property>
    13. </class>
    14. </constraint-mapping>
  • PHP

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. // DON'T forget the following use statement!!!
    4. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    5. use Symfony\Component\Validator\Constraints as Assert;
    6. class User
    7. {
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addConstraint(new UniqueEntity([
    11. 'fields' => 'email',
    12. ]));
    13. $metadata->addPropertyConstraint('email', new Assert\Email());
    14. }
    15. }

Caution

This constraint doesn’t provide any protection against race conditions. They may occur when another entity is persisted by an external process after this validation has passed and before this entity is actually persisted in the database.

Caution

This constraint cannot deal with duplicates found in a collection of items that haven’t been persisted as entities yet. You’ll need to create your own validator to handle that case.

Options

em

type: string

The name of the entity manager to use for making the query to determine the uniqueness. If it’s left blank, the correct entity manager will be determined for this class. For that reason, this option should probably not need to be used.

entityClass

type: string

By default, the query performed to ensure the uniqueness uses the repository of the current class instance. However, in some cases, such as when using Doctrine inheritance mapping, you need to execute the query in a different repository. Use this option to define the fully-qualified class name (FQCN) of the Doctrine entity associated with the repository you want to use.

errorPath

type: string default: The name of the first field in fields

If the entity violates the constraint the error message is bound to the first field in fields. If there is more than one field, you may want to map the error message to another field.

Consider this example:

  • Annotations

    1. // src/Entity/Service.php
    2. namespace App\Entity;
    3. use Doctrine\ORM\Mapping as ORM;
    4. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    5. /**
    6. * @ORM\Entity
    7. * @UniqueEntity(
    8. * fields={"host", "port"},
    9. * errorPath="port",
    10. * message="This port is already in use on that host."
    11. * )
    12. */
    13. class Service
    14. {
    15. /**
    16. * @ORM\ManyToOne(targetEntity="App\Entity\Host")
    17. */
    18. public $host;
    19. /**
    20. * @ORM\Column(type="integer")
    21. */
    22. public $port;
    23. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Service:
    3. constraints:
    4. - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
    5. fields: [host, port]
    6. errorPath: port
    7. message: 'This port is already in use on that host.'
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Service">
    7. <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
    8. <option name="fields">
    9. <value>host</value>
    10. <value>port</value>
    11. </option>
    12. <option name="errorPath">port</option>
    13. <option name="message">This port is already in use on that host.</option>
    14. </constraint>
    15. </class>
    16. </constraint-mapping>
  • PHP

    1. // src/Entity/Service.php
    2. namespace App\Entity;
    3. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Service
    6. {
    7. public $host;
    8. public $port;
    9. public static function loadValidatorMetadata(ClassMetadata $metadata)
    10. {
    11. $metadata->addConstraint(new UniqueEntity([
    12. 'fields' => ['host', 'port'],
    13. 'errorPath' => 'port',
    14. 'message' => 'This port is already in use on that host.',
    15. ]));
    16. }
    17. }

Now, the message would be bound to the port field with this configuration.

fields

type: array | string [default option]

This required option is the field (or list of fields) on which this entity should be unique. For example, if you specified both the email and name field in a single UniqueEntity constraint, then it would enforce that the combination value is unique (e.g. two users could have the same email, as long as they don’t have the same name also).

If you need to require two fields to be individually unique (e.g. a unique email and a unique username), you use two UniqueEntity entries, each with a single field.

groups

type: array | string

It defines the validation group or groups this constraint belongs to. Read more about validation groups.

ignoreNull

type: boolean default: true

If this option is set to true, then the constraint will allow multiple entities to have a null value for a field without failing validation. If set to false, only one null value is allowed - if a second entity also has a null value, validation would fail.

message

type: string default: This value is already used.

The message that’s displayed when this constraint fails. This message is by default mapped to the first field causing the violation. When using multiple fields in the constraint, the mapping can be specified via the errorPath property.

Messages can include the {{ value }} placeholder to display a string representation of the invalid entity. If the entity doesn’t define the __toString() method, the following generic value will be used: “Object of class __CLASS__ identified by <comma separated IDs>”

You can use the following parameters in this message:

ParameterDescription
{{ value }}The current (invalid) value

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

repositoryMethod

type: string default: findBy

The name of the repository method used to determine the uniqueness. If it’s left blank, findBy() will be used. The method receives as its argument a fieldName => value associative array (where fieldName is each of the fields configured in the fields option). The method should return a [countable PHP variable](https://www.php.net/manual/en/function.is-countable.php "is_countable").

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.