2016-11-28 106 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