T
T
TANK_IST2017-10-08 22:38:10
symfony
TANK_IST, 2017-10-08 22:38:10

How to add validation on unique field in doctrine?

Essence

<?php
namespace OwrBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="OwrBundle\Entity\Repository\UserRepository")
 * @ORM\Table(name="`user`")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity(
 *     fields={"username", "phone"},
 *     message="duplicate"
 * )
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", name="user_id")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", name="email", unique=true)
     * @Assert\Email(
     *     message = "email",
     *     checkMX = true
     * )
     */
    protected $username;

    /**
     * @ORM\Column(type="string", length=13, unique=true)
     * @Assert\Regex(
     *     pattern = "/^\+\d{12}$/",
     *     message = "correct"
     * )
     */
    protected $phone;

    /**
    ...
    **/
}

I enter phone numbers that are already in the database.
But the validator does not return an error.
The database itself gives it:
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "uniq_8d93d649444f97dd"
DETAIL: Key (phone)=(+180863723139) already exists.

How to make the validator catch errors?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jaxel, 2017-10-09
@TANK_IST

You have a UniqueEntity validator for two fields at once. It checks if the combination "username" and "phone" is unique. You need to separate them into two separate validators rather than specifying both fields in one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question