Gaylord.P
Gaylord.P

Reputation: 1468

UniqueEntity don't check with update

With Doctrine and Symfony 4.1 I create User entity with UniqueEntity

/**
 * User
 * 
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="user")
 * @UniqueEntity(
 *     fields = "email",
 *     message = "email.already_taken"
 * )
 */
class User {
    ...

An exception occurred while executing 'UPDATE user SET email = ? WHERE id = ?' with params ["[email protected]", 14]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'UNIQ_8D93D649E7927C74'

Why UniqueEntity do not test the update ?

Upvotes: 0

Views: 1038

Answers (3)

Giray Kefelioglu
Giray Kefelioglu

Reputation: 213

For annonation you have to add Lifecycle Callbacks and add Doctrine UniqueConstraint

use Doctrine\ORM\Mapping\UniqueConstraint;

/**
 * User
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="user", uniqueConstraints{@UniqueConstraint(columns={"email"})})
 * @UniqueEntity(
 *     fields = "email",
 *     message = "email.already_taken"
 * )
 */
class User {}

/**
 * @ORM\PrePersist
 */
public function setCreatedAtValue()
{
    $this->createdAt = new \DateTime();
}

more information https://symfony.com/doc/4.1/doctrine/lifecycle_callbacks.html

Upvotes: 0

mcek
mcek

Reputation: 490

Maybe try validate entity before flush? https://symfony.com/doc/4.1/validation.html#using-the-validator-service

$errors = $validator->validate($updatedUser);

if (count($errors) > 0) {
    $errorsString = (string) $errors;

    return new Response($errorsString);
}

Errors should contain information that user already exist.

Upvotes: 0

Denis Alimov
Denis Alimov

Reputation: 2891

you can add groups to the constraint groups={"new", "edit"}. Then use this groups in forms like described here

Upvotes: 2

Related Questions