0

I've tried to implement the unique entity from Symfony and when I try to insert with same email, it doesn't show the error message, but it shows instead a PHP Error.

The error :

An exception occurred while executing 'INSERT INTO user (id, email, firstname, lastname, password, registered_at, is_verified, forgotten_password_token, forgotten_password_requested_at, farm_id, discr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["8006dc22-226a-4fe1-b6f2-0baf0ac1767f", "[email protected]", "Laurent", "Sanson", "$argon2id$v=19$m=65536,t=4,p=1$iKtkpJZhi\/SAAQDip2YTyQ$7n2+LRh8p+KQEN\/RzECrFDsxiouNAMyKuB6cdhMBIgY", "2021-01-05 19:53:36", 0, null, null, "478c39c3-12b3-4f0b-a877-b2d9edfbd6c5", "producer"]:

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

The beginning of my UserClass :

<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\UserRepository;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Serializable;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Uid\Uuid;

/**
 * Class User
 * @package App\Entity
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"producer"="App\Entity\Producer", "customer"="App\Entity\Customer"})
 * @UniqueEntity(
 *     fields="email",
 *     errorPath="email",
 *     message="Cet e-mail est déjà associé à un compte",
 *     entityClass="App\Entity\User"
 * )
 */
abstract class User implements UserInterface, Serializable, EquatableInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="uuid")
     */
    protected Uuid $id;

    /**
     * @ORM\Column(unique=true)
     * @Assert\NotBlank
     * @Assert\Email
     */
    protected string $email = "";
}

I've tried many things but nothing seems to work

/// EDIT /// The registration depends on the role but it'll be an user for sure. There is an inheritence between the User and the Customer/Producer My RegistrationController :

/**
     * @Route("/register/{role}", name="app_register")
     * @param string $role
     * @param Request $request
     * @param UserPasswordEncoderInterface $passwordEncoder
     * @return Response
     */
    public function register(string $role, Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $user = Producer::ROLE === $role ? new Producer() : new Customer();
        $user->setId(Uuid::v4());
        $form = $this->createForm(RegistrationFormType::class, $user, [
            "validation_groups" => ["Default" => "password"]
        ])->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->setPassword(
                $passwordEncoder->encodePassword($user, $user->getPlainPassword())
            );
            $this->getDoctrine()->getManager()->persist($user);
            $this->getDoctrine()->getManager()->flush();
            $this->addFlash("success", "Votre inscription a été effectuée avec succès");

            return $this->redirectToRoute('index');
        }

        return $this->render('ui/security/register.html.twig', [
            'registrationForm' => $form->createView(),
        ]);
    }
5
  • Could you please provide the code that create your user Commented Jan 5, 2021 at 20:11
  • Hello, can you try to add @Assert\Unique assertion for email and validate it before trying to save? Best Commented Jan 5, 2021 at 20:14
  • you could also catch the exception on flush and render the error, but i would already in frontend check the availability of the entered email Commented Jan 6, 2021 at 10:24
  • 1
    @Mcsky No problem, I'll post it tonight Commented Jan 6, 2021 at 10:52
  • @l13 I'll try this tonight, thanks Commented Jan 6, 2021 at 10:52

3 Answers 3

1

The error in validation groups, it should be array of group like:

['Default', 'password']
Sign up to request clarification or add additional context in comments.

Comments

1

So instead of

$form = $this->createForm(RegistrationFormType::class, $user, [
            "validation_groups" => ["Default" => "password"]
        ])->handleRequest($request);

I should do like this ?

$form = $this->createForm(RegistrationFormType::class, $user, [
            "validation_groups" => ["Default" , "password"]
        ])->handleRequest($request);

1 Comment

I've tried like this but it says that the User class does not exist... I'm desperate
1

I've finally found it !!! :)

I had to remove the class param in the Unique entity annotation like :

 @UniqueEntity(fields="email", message="Cet e-mail est déjà associé à un compte")

Cheers guys !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.