2016-11-28 102 views
0

对于我的项目,我需要在注册后重定向用户。为了实现这一目标,我创建了一个EventListener如下所述:Symfony2 FOSuserBundle事件REGISTRATION_COMPLETED未触发

我的事件监听器:

namespace UserBundle\EventListener; 

use FOS\UserBundle\FOSUserEvents; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; 

class RegistrationConfirmListener implements EventSubscriberInterface 
{ 
    private $router; 

    public function __construct(UrlGeneratorInterface $router) 
    { 
     $this->router = $router; 
    } 

    /** 
    * {@inheritDoc} 
    */ 
    public static function getSubscribedEvents() 
    { 
     return array(
      FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm' 
     ); 
    } 

    public function onRegistrationConfirm(GetResponseUserEvent $event) 
    { 
     $url = $this->router->generate('standard_user_registration_success'); 
     $event->setResponse(new RedirectResponse($url)); 
    } 
} 

我把它注册为我service.yml服务:

services: 
    rs_user.registration_complet: 
     class: UserBundle\EventListener\RegistrationConfirmListener 
     arguments: [@router] 
     tags: 
      - { name: kernel.event_subscriber } 

我需要在我的RegistrationController中使用它,但我不明白如何触发它。 在这里,我registerAction

public function registerAction(Request $request) 
{ 
     $em = $this->get('doctrine.orm.entity_manager'); 
     //Form creation based on my user entity 
     $user = new StandardUser(); 
     $form = $this->createForm(RegistrationStandardUserType::class, $user); 
     $form->handleRequest($request); 

     if ($form->isSubmitted() && $form->isValid()) { 
      $user  ->setEnabled(true); 
      $em   ->persist($user); 
      $em   ->flush(); 
      if ($user){ 
       $dispatcher = $this->get('event_dispatcher'); 
       $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM); 
      } 
     } 

    return $this->render('UserBundle:Registration:register.html.twig', array(
      'form' => $form->createView() 
    )); 
} 

我不明白的Symfony2 documentation这个话题无论是我需要传递给->dispatch()功能触发我的事件是什么。

Type error: Argument 1 passed to 
UserBundle\EventListener\RegistrationConfirmListener::onRegistrationConfirm() 
must be an instance of UserBundle\EventListener\GetResponseUserEvent, 
instance of Symfony\Component\EventDispatcher\Event given 
500 Internal Server Error - FatalThrowableError 

回答

2

你的听众宣布,它被订阅FOSUserEvents::REGISTRATION_CONFIRM但你调度FOSUserEvents::REGISTRATION_COMPLETED

[编辑] 当我注册我的用户我得到这个错误。要触发它,你需要派遣FOSUserEvents::REGISTRATION_CONFIRM事件

编辑以匹配您的编辑,你需要传递的事件在您的服务tags

- { name: 'kernel.event_subscriber', event: 'fos_user.registration.confirm'} 
+0

我的不好,但我已经尝试过了一个得到一个错误,我更新了我的帖子(对不起,浪费时间) – Gauthier

+1

编辑以反映您更新的错误 – skrilled

+0

好的,谢谢您的更新。该事件现在按照您的帖子中的描述通过,但我仍然有错误。我认为这可能是我发送它的方式,但仍然是,我不知道... – Gauthier