Markdown

[Symfony] UniqueEntity

https://symfony.com/doc/current/reference/constraints/UniqueEntity.html

https://stackoverflow.com/questions/12001753/why-is-my-symfony2-uniqueentity-constraint-not-working-at-all

// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

// DON'T forget this use statement!!!
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity("email")
 */
class Author
{
    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    protected $email;

    // ...
}
---

errorPath

typestring 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
     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
    // src/AppBundle/Entity/Service.php
    namespace AppBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    
    /**
     * @ORM\Entity
     * @UniqueEntity(
     *     fields={"host", "port"},
     *     errorPath="port",
     *     message="This port is already in use on that host."
     * )
     */
    class Service
    {
        /**
         * @ORM\ManyToOne(targetEntity="Host")
         */
        public $host;
    
        /**
         * @ORM\Column(type="integer")
         */
        public $port;
    }

留言