shuba.ivan
shuba.ivan

Reputation: 4061

Symfony Doctrine UniqueEntity

I have UniqueEntity field email and I use SoftDeleteable

        filters:
        softdeleteable:
            class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
            enabled: true


 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @UniqueEntity(
 *     fields="email",
 *     errorPath="not valid",
 *     message="This email is already in use."
 * )

and when in my DB I have user with deletedAt some date and find entity by email

$user_by_email = $em->getRepository('ArtelProfileBundle:Users')->findOneByEmail($email);

I have null and this is ok. But when I create new user I have error

Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'UNIQ_1483A5E9E7927C74'",

this my action. But have error when flush, when validate not error. Help

        $data = $request->request->all();
        $data = $this->get('serializer')->serialize($data, 'json');
        $user = $this->get('serializer')->deserialize($data, 'Artel\ProfileBundle\Entity\Users', 'json');

        if (count($errors = $this->get('validator')->validate($user)) > 0) {
            $view = $this->view((string) $errors, 400);

            return $this->handleView($view);
        }

        $em->persist($user);
        $em->flush();

Upvotes: 2

Views: 471

Answers (1)

tchap
tchap

Reputation: 3432

Well, you have a unique constraint on email, and you try to insert a new user with an already existing email .. so the error makes perfect sense.

SoftDeleteable merely adds a flag in your DB, but do not change the way unique fields are managed.

What you can do, though, is to make the pair email and deleted_at unique, instead of just the email field. You will only get this error when there is a not deleted row where email is the same.

Or, alternatively, delete the email when you "soft delete" a user, for instance. But I don't recommend it.

Upvotes: 1

Related Questions