如何通过symfony的服务发送前任错误

时间:2017-11-27 13:33:30

标签: php symfony events fosuserbundle

我不习惯寻求帮助,但对于这个问题,我承认我自己无法解决。

我在同一页面上有2个表单(来自fosuserbundle的loginform和registerform) 两种形式都有效。

现有用户尝试注册时出现问题。

我创建了一个RegistrationFailureListener,如果已经存在电子邮件(例如),则会在同一页面上重定向用户。

register/路线上显示的错误不会在此页面上显示2个表格。

我不知道如何在我的网页上发送这些表单错误。

对不起,我的英文!

我的代码:

 <?php
    namespace TNS\UserBundle\EventListener;
    use FOS\UserBundle\Event\FormEvent;
    use FOS\UserBundle\FOSUserEvents;
    use FOS\UserBundle\Mailer\MailerInterface;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpFoundation\Session\SessionInterface;
    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;


    class RegistrationListener implements EventSubscriberInterface
    {

        /**
         * @var UrlGeneratorInterface
         */
        private $router;
        /**
         * @var TokenGeneratorInterface
         */
        private $tokenGenerator;
        /**
         * @var SessionInterface
         */
        private $session;
        /**
         * @var MailerInterface
         */
        private $mailer;


        /**
         * RegistrationSuccessListener constructor.
         * @param UrlGeneratorInterface $router
         * @param TokenGeneratorInterface $tokenGenerator
         * @param SessionInterface $session
         * @param MailerInterface $mailer
         */
        public function __construct(UrlGeneratorInterface $router, TokenGeneratorInterface $tokenGenerator, SessionInterface $session, MailerInterface $mailer)
        {
            $this->router = $router;
            $this->tokenGenerator = $tokenGenerator;
            $this->session = $session;
            $this->mailer = $mailer;
        }

        /**
         * Returns an array of event names this subscriber wants to listen to.
         *
         * The array keys are event names and the value can be:
         *
         *  * The method name to call (priority defaults to 0)
         *  * An array composed of the method name to call and the priority
         *  * An array of arrays composed of the method names to call and respective
         *    priorities, or 0 if unset
         *
         * For instance:
         *
         *  * array('eventName' => 'methodName')
         *  * array('eventName' => array('methodName', $priority))
         *  * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
         *
         * @return array The event names to listen to
         */
        public static function getSubscribedEvents()
        {
            return array(
                FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
                FOSUserEvents::REGISTRATION_FAILURE => 'onRegistrationFailure'
            );
        }

        public function onRegistrationFailure( FormEvent $event ) {        
            $url = $this->router->generate('tns_core_homepage');
            $event->setResponse(new RedirectResponse($url));

        }
 public function onRegistrationSuccess(FormEvent $event)
    {
        /** @var $user \FOS\UserBundle\Model\UserInterface */
        $user = $event->getForm()->getData();

        $user->setEnabled(false);
        if (null === $user->getConfirmationToken()) {
            $user->setConfirmationToken($this->tokenGenerator->generateToken());
        }

        $this->session->set('fos_user_send_confirmation_email/email', $user->getEmail());

        $url = $this->router->generate('fos_user_registration_check_email');
        $event->setResponse(new RedirectResponse($url));

    }
}

我的RegisterController与fosuser registercontroller

相同

1 个答案:

答案 0 :(得分:0)

好的伙计们! 我解决了我的问题。 我创建了一个新用户:

<?php
namespace TNS\UserBundle\EventListener;


use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;

class RegistrationFailureListener implements EventSubscriberInterface
{
    /**
     * @var EngineInterface
     */
    private $templating;


    public function __construct( TwigEngine $templating) {
        $this->templating = $templating;
    }

    /**
     * Returns an array of event names this subscriber wants to listen to.
     *
     * The array keys are event names and the value can be:
     *
     *  * The method name to call (priority defaults to 0)
     *  * An array composed of the method name to call and the priority
     *  * An array of arrays composed of the method names to call and respective
     *    priorities, or 0 if unset
     *
     * For instance:
     *
     *  * array('eventName' => 'methodName')
     *  * array('eventName' => array('methodName', $priority))
     *  * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
     *
     * @return array The event names to listen to
     */
    public static function getSubscribedEvents() {
        return array(
            FOSUserEvents::REGISTRATION_FAILURE => 'onRegistrationFailure'
        );
    }

    public function onRegistrationFailure( FormEvent $event ) {
        $form = $event->getForm();
        $response = $this->templating->render('TNSUserBundle:Security:login.html.twig', array(
            'form'=>$form->createView()
        ));
        $event->setResponse(new Response($response));

    }

我改变了我的观点:

{% trans_default_domain 'FOSUserBundle' %}
    {% if error is defined and error is not null%}
        <div class="alert alert-danger col col-md-12">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}
    <div class="p-0 card col col-md-5 col-12">
            <h3 class="p-2 bg-primary text-white">Se connecter</h3>
            <form action="{{ path("fos_user_security_check") }}" method="post" class="p-2">
                {% if csrf_token is defined%}
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}"/>
                {% endif %}
                <div class="form-group">
                    <label for="username">{{ 'security.login.username'|trans }}</label>
                    <input type="text" id="username" class="form-control" name="_username" value="{% if last_username is defined %}{{ last_username }}{% endif %}"
                           required="required"/>
                </div>
                <div class="form-group">
                    <label for="password">{{ 'security.login.password'|trans }}</label>
                    <input type="password" id="password" class="form-control" name="_password" required="required"/>
                </div>
                <div class="form-check">
                    <label class="form-check-label">
                        <input type="checkbox" id="remember_me" class="form-check-input" name="_remember_me" value="on"/>
                        {{ 'security.login.remember_me'|trans }}
                    </label>
                </div>
                <div class="form-group" align="center" style="margin-top: 54%">
                <input type="submit" class="btn btn-primary" id="_submit" name="_submit"
                       value="{{ 'security.login.submit'|trans }}"/>
                </div>
            </form>
    </div>
{% if form is defined %}
    <div class="p-0 card col col-md-5 col-12">
        <h3 class="p-2 bg-primary text-white">S'inscrire</h3>
        {{  form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register p-2'}}) }}
        {{ form_widget(form) }}
        {{ form_errors(form) }}
        {{ form_widget(form._token) }}
        <div align="center">
            <input type="submit" class="btn btn-primary" value="{{ 'registration.submit'|trans }}" />
        </div>
        {{ form_end(form) }}
    </div>
{% else %}
    <div class="p-0 card col col-md-5 col-12">
        <h3 class="p-2 bg-primary text-white">S'inscrire</h3>
        {{ render(controller('TNSUserBundle:Registration:register')) }}
    </div>
{% endif %}

最后在我看来我测试是否定义了表单var,如果是,我显示表单,否则我从RegisterController调用表单

我不知道这是否正确,但我的表单错误会显示,并且我会在右页重定向!

如果它可以帮助别人......