0

I have a Symfony entity with @UniqueEntity annotation. I use it so I don't get double records in my database with the same email but I don't want to return to the user that the email is already in the database (privacy reasons).

How can I use @UniqueEntity but catch the error and return to the user a success message?

Controller code:

    public function register(Request $request, EntityManagerInterface $entityManager, TranslatorInterface $translator): Response
    {
        $success = false;

        $newsletter = new Newsletter();
        $form = $this->createForm(NewsletterType::class, $newsletter);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
                $newsletter = $form->getData();

                $entityManager->persist($newsletter);
                $entityManager->flush();

                $this->addFlash('success', $translator->trans('newsletter.signed_up'));

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

        return $this->render('landing/landing.html.twig', [
            'newsletter_form' => $form->createView(),
            'newsletter_success' => $success,
        ]);
    }
10
  • Can you show the code, e.g. from your controller where you want to catch the error?
    – dbrumann
    Commented May 25, 2020 at 11:16
  • @dbrumann added, it's simple controller with just one form, nothing complicated
    – nass
    Commented May 25, 2020 at 11:51
  • 1
    All websites tell you that the username or email is already taken, so how the user will know that the email is already exists ?
    – hous
    Commented May 25, 2020 at 16:51
  • @hous but when you enter email on the reset password, for example, it doesn't say whether an account with that e-mail address is in a database for security/privacy reasons. That's what I want to achieve here. I don't want someone else other than the owner of the e-mail address know whether account exists / is subscribed to newsletter.
    – nass
    Commented May 25, 2020 at 17:43
  • for reset password , yes we don't say that the email exists or not but you can say "if the email exists you will recieve an email ...".
    – hous
    Commented May 25, 2020 at 17:51

1 Answer 1

0

Basically, two possibilities:

  1. Check if inserted email is already in DB performing an explicit query (keep @UniqueConstraint annotation in order to preserve data integrity).
  2. Wrap entity manager operation in try-catch block, as follows (check also this answer)

    try {
      $entityManager->persist($newsletter);
      $entityManager->flush();
    } catch (UniqueConstraintViolationException $e) {
      // you can check if the exception is raised by email field, somehow, or just "mask" with a general error
    }
    

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.