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

时间:2017-10-13 16:39:54

标签: 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(),
    ));
}

感谢您的帮助

4 个答案:

答案 0 :(得分:2)

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

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

// 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;

    // ...
}

向类和使用语句的@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(),
    ));
}

有关详情:

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

答案 1 :(得分:1)

// Pass in the entity manager to your form via options
// Do this before you call $this->createForm:
// $options['entityManager'] = $this->getDoctrine()->getManager();
// then call $form = $this->createForm(InviteType::class, $invite, $options);

// Inside your form type i.e. InviteType
$em = $options['entityManager'];

$builder->addEventListener(
    FormEvents::PRE_SUBMIT,
    function (FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
        $user = $data['user']; // this needs to be whatever you called user in your form
        $userRepo = $em->getRepository('User'); // this needs to be the location of your user repository
        if ($userRepo->findOneBy(['user' => $user])) { // you need to pick a field that determines how you will search for the user via the repository
            $form->addError(new FormError('User already exists'));
        }
    }
);

答案 2 :(得分:0)

<div class="container accroche">
    <h5>{{ 'Inscription aux évenements'|trans }}</h5>
    <p>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500,
        quand un peintre anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique,
        sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment,
        par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker.
    </p>
</div>
{{ form_start(form, {attr: {novalidate: 'novalidate','id':'formValidate'}}) }}
<div class="middle">
    <div class="middle_form">
        <div class="container">

            <div class="stepwizard">
                <div class="stepwizard-row setup-panel col-md-12 text-center">
                    <div class="stepwizard-step col-md-3">
                        <a href="#step-1" type="button" class="btn btn-primary btn-circle">1</a>
                    </div>
                    <div class="stepwizard-step col-md-3">
                        <a href="#step-2" type="button" class="btn btn-default btn-circle" disabled="disabled">2</a>
                    </div>
                    <div class="stepwizard-step col-md-3">
                        <a href="#step-3" type="button" class="btn btn-default btn-circle" disabled="disabled">3</a>
                    </div>
                    <div class="stepwizard-step col-md-3">
                        <a href="#step-4" type="button" class="btn btn-default btn-circle" disabled="disabled">4</a>
                    </div>
                </div>
            </div>

            <div class="row setup-content" id="step-1">
                <div class="col-md-12">
                    <h3>{{ 'Informations invités'|trans }}</h3>
                    <div class="row">
                        <div class="input-field col-12">
                            {{ form_widget(form.name, {'attr': {'class': 'validate', 'id': 'last_name'}}) }}
                            {{ form_errors(form.name) }}
                            <label for="last_name">{{ 'Nom'|trans }} <sup>*</sup></label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col-12">
                            {{ form_widget(form.surname, {'attr': {'class': 'validate', 'id': 'surname'}}) }}
                            {{ form_errors(form.surname) }}
                            <label for="surname">{{ 'Prénom'|trans }} <sup>*</sup></label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col-12">
                            {{ form_widget(form.email, {'attr': {'class': 'validate', 'id': 'email'}}) }}
                            {{ form_errors(form.email) }}
                            <label for="email">{{ 'E-mail'|trans }} <sup>*</sup></label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <label>{{ 'Présence'|trans }} <sup>*</sup></label>
                            {{ form_widget(form.dispo, {'attr': {'class': 'validate', 'id': 'dispo'}}) }}
                            {{ form_errors(form.dispo) }}
                        </div>
                    </div>
                    <button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
                </div>
            </div>

            <div class="row setup-content" id="step-2">
                <div class="col-md-12">
                    <h3>{{ 'Informations participants'|trans }}</h3>
                    <div class="row">
                        <ul class="customers"
                            data-prototype="{{ form_widget(form.customers.vars.prototype)|e('html_attr') }}">
                            {% for customers in form.customers %}
                                <div class="row">
                                    <div class="input-field col-12">
                                        {{ form_row(customers.name, {'attr': {'class': 'validate', 'id': 'name'}}) }}
                                        {{ form_errors(customers.name) }}
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="input-field col-12">
                                        {{ form_row(customers.surname, {'attr': {'class': 'validate', 'id': 'surname'}}) }}
                                        {{ form_errors(customers.surname) }}
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="input-field col-12">
                                        {{ form_row(customers.old) }}
                                        {{ form_errors(customers.old) }}
                                    </div>
                                </div>
                            {% endfor %}
                        </ul>
                    </div>
                    <button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
                    <button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
                </div>
            </div>

            <div class="row setup-content" id="step-3">
                <div class="col-md-12">
                    <h3>Logements</h3>
                    <div class="row">
                        <div class="input-field col-12">
                            {{ form_widget(form.housing, {'attr': {'class':'validate'}}) }}
                            {{ form_errors(form.housing) }}
                            <label>{{ 'Comment allez vous vous logez ?'|trans }} <sup>*</sup></label>
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col-12">
                            {{ form_widget(form.hotel, {'attr': {'class':'validate'}}) }}
                            {{ form_errors(form.hotel) }}
                            <label>{{ 'Hôtel'|trans }} <sup>*</sup></label>
                        </div>
                    </div>
                    <button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
                    <button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
                </div>
            </div>

            <div class="row setup-content" id="step-4">
                <div class="col-md-12">
                    <h3>{{ 'Arrivée/Départ'|trans }}</h3>
                    <div class="row">
                        <div class="col-12">
                            <label>{{ 'Date d\'arrivée'|trans }} <sup>*</sup></label>
                            {#<input class="datepicker" type="text" id="dateArrival" name="form[dateArrival]"/>#}
                            {{ form_widget(form.dateArrival, {'attr': {'class': 'datepicker validate'}}) }}
                            {{ form_errors(form.dateArrival) }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <label>{{ 'Date de départ'|trans }} <sup>*</sup></label>
                            {#<input class="datepicker" type="text" id="dateDeparture" name="form[dateDeparture]"/>#}
                            {{ form_widget(form.dateDeparture, {'attr': {'class': 'datepicker validate'}}) }}
                            {{ form_errors(form.dateDeparture) }}
                        </div>
                    </div>
                    <div class="row">
                        <div class="input-field col-12">
                            {{ form_widget(form.transport, {'attr': {'class':'validate'}}) }}
                            {{ form_errors(form.transport) }}
                            <label>{{ 'Transport utilisé'|trans }} <sup>*</sup></label>
                        </div>
                    </div>
                    <div class="btn-center">
                    <button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
                    {{ form_widget(form.save, {'attr': {'class':'btn btn-success', 'id':'SaveAccount'}}) }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


{{ form_widget(form.dateArrival, {'attr': {'class': 'hidden'}}) }}
{{ form_widget(form.dateDeparture, {'attr': {'class': 'hidden'}}) }}
{{ form_end(form) }}

答案 3 :(得分:-1)

首先,获取ID $id = #YourId;。然后,您可以使用SQL选择用户。 SELECT * FROM [user_table] WHERE id = $id;如果结果包含用户,则该用户存在。