For my project, I need to redirect the user after registration. In order to achieve that, I created an EventListener
as described below :
My Event Listener :
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));
}
}
I registered it as a service in my service.yml :
services:
rs_user.registration_complet:
class: UserBundle\EventListener\RegistrationConfirmListener
arguments: [@router]
tags:
- { name: kernel.event_subscriber }
And I need to use it in my RegistrationController but I don't understand how to trigger it.
Here in my 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()
));
}
I don't understand the Symfony2 documentation about the subject neither what I need to pass to the ->dispatch()
function to trigger my event.
[EDIT] I get this error when I register my user :
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