Reputation: 1468
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 {
...
INSERT
) the error is triggered : goodUPDATE
) user with another exist email, I have error : not goodAn 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
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
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
Reputation: 2891
you can add groups to the constraint groups={"new", "edit"}
. Then use this groups in forms like described here
Upvotes: 2