Symfony 检查用户是否存在于数据库中

2 php mysql symfony

我正在我的控制器中寻找解决方案,以便在发送表单之前检查用户是否已存在于数据库中。这是我想实施的行动。

/**
 * Creates a new invite entity.
 *
 * @Route("/inscription", name="invite_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $invite = new Invite();

    $form = $this->createForm(InviteType::class, $invite);

    if ($request->isMethod('POST')) {
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($invite);
            $em->flush();

            $this->get('app_mailer')->sendMailInscriptionMjml($invite, $this->getParameter('client_mail_to'));

            $this->get('session')->getFlashBag()->add('success', 'Votre inscription à été pris en compte.');
        } else {
            $this->get('session')->getFlashBag()->add('error', 'Une erreur est survenue.');
        }

        return $this->redirect($this->generateUrl('invite_show', array('id' => $invite->getId())));
    }

    return $this->render('@App/invite/new.html.twig', array(
        'invite' => $invite,
        'form' => $form->createView(),
    ));
}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助

Rob*_*ade 6

您不需要在控制器中执行此操作。这是基本的实体验证,Symfony 带有内置约束来处理此类事情。

假设您在 Symfony 应用程序中使用类似于下面的用户实体,您只需要对用户类应用唯一的验证约束,并指定要测试哪些属性的唯一性。此示例将通过 email验证用户是否唯一,如果不是,则抛出异常。

// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/** @UniqueEntity(
  * fields={"email"},
  * errorPath="email",
  * message="It appears you have already registered with this email."
  *)
  */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    protected $email;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

注意类上的@UniqueEntity("email")注释和使用语句。当然,您需要在用户类中采用这种逻辑。

// controller action
public function newAction(Request $request)
{
    $invite = new Invite();

    $form = $this->createForm(InviteType::class, $invite);

    if ($request->isMethod('POST')) {
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($invite);
            $em->flush();

            $this->get('app_mailer')->sendMailInscriptionMjml(
              $invite, $this->getParameter('client_mail_to')
            );

            $this->get('session')->getFlashBag()
              ->add('success', 'Votre inscription à été pris en compte.');

            return $this->redirect(
              $this->generateUrl(
                'invite_show', array(
                  'id' => $invite->getId()
                )
              )
            );
         }
    }

    return $this->render('@App/invite/new.html.twig', array(
        'invite' => $invite,
        'form' => $form->createView(),
    ));
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息:

https://symfony.com/doc/current/reference/constraints/UniqueEntity.html