Override Registration Controller with fosuser Cannot autowire service "App\Controller\RegistrationController" - symfony

I am trying to override the FosUserBundle Registry Controller, but the following error appears:
Cannot autowire service "App\Controller\RegistrationController": argument "$formFactory" of method
"FOS\UserBundle\Controller\RegistrationController::__construct()"
references interface "FOS\UserBundle\Form\Factory\FactoryInterface" but no such service exists.
You should maybe alias this interface to one of these existing services: "fos_user.profile.form.factory", "fos_user.registration.form.factory", "fos_user.change_password.form.factory",
"fos_user.resetting.form.factory". Did you create a class that implements this interface?
I'm using Symfony4 and this is my RegistrationController.php code.
I've tried multiple ways, but I can't find a way to make it work.
class RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
$form = $this->get('fos_user.registration.form.factory');
$formHandler = $this->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->getParameter('fos_user.registration.confirmation.enabled');
die("Hello");
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
if ($confirmationEnabled) {
$this->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
// $this->authenticateUser($user);
$route = 'users_edit';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->get('router')->generate($route, array("id" => $user->id));
return new RedirectResponse($url);
}
return $this->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.twig', array(
'form' => $form->createView()
));
}
}
?>

I had the same problem , with SF4 and FOSUserBundle. After looking around for half a day I come with a solution. I use some material from #thibaut and adapt it to SF 4.2.
I inject the services needed by fos user registration controlleur and give FOS\UserBundle\Form\Factory\FactoryInterface an alias
config/services.yaml
app.controller.register:
class: App\Controller\bundles\FOSUserBundle\RegistrationController
arguments:
$eventDispatcher: '#event_dispatcher'
$formFactory: '#fos_user.registration.form.factory'
$userManager: '#fos_user.user_manager'
$tokenStorage: 'security.token_storage'
calls:
- method: setContainer
arguments:
- '#service_container'
public: true
FOS\UserBundle\Form\Factory\FactoryInterface:
alias: 'fos_user.registration.form.factory'
public: true
Then in my registration controller, I redeclare a constructor and save formfactory to be use in the controller
App\Controller\bundles\FOSUserBundle
protected $formFactory;
public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage, $serviceContainer=null)
{
$this->setContainer($serviceContainer);
$this->formFactory = $formFactory;
parent::__construct($eventDispatcher, $formFactory, $userManager, $tokenStorage);
}
use the declare $formfactory in my action
/**
* #Route("/register", name="registration")
*/
public function registerAction(Request $request)
{
/** #var $formFactory FactoryInterface */
$formFactory = $this->formFactory;
/** #var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
Hope it also help you guys

work in symfony 4.2
services.yaml
App\Controller\RegistrationController:
arguments:
$formFactory: '#fos_user.registration.form.factory'
and controller
use FOS\UserBundle\Controller\RegistrationController as Base;
class RegistrationController extends Base
{
private $eventDispatcher;
private $formFactory;
private $userManager;
private $tokenStorage;
public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage)
{
parent::__construct($eventDispatcher, $formFactory,$userManager, $tokenStorage);
$this->eventDispatcher = $eventDispatcher;
$this->formFactory = $formFactory;
$this->userManager = $userManager;
$this->tokenStorage = $tokenStorage;
}

I don't know which version of FOSUserBundle are you using but there is no official support for sf4 yet - see release notes. You can try dev-master version and follow this issue to make it work.

You should use hooks and avoid override controllers in FOSUserBundel v2.x
More information you can read on the page: http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html

I had to use an alias for the FOS services that were refusing to autowire in my config/services.yaml
FOS\UserBundle\Form\Factory\FormFactory: '#fos_user.registration.form.factory'
As seen in vendor/friendsofsymfony/user-bundle/Resources/config/registration.xml

Hello i think i have found a way to handle this problem:
Define your service:
app.controller.register:
class: AppBundle\Controller\RegisterController
arguments: ['#service_container']
public: true
then your controller
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
/**
* #Route(service="app.controller.register")
*/
class RegisterController extends BaseController
{
public function __construct($serviceContainer=null)
{
$this->setContainer($serviceContainer);
$eventDispatcher=$this->container->get('event_dispatcher');
$formFactory=$this->container->get('fos_user.registration.form.factory');
$userManager=$this->container->get('fos_user.user_manager');
$tokenStorage=$this->container->get('security.token_storage');
parent::__construct($eventDispatcher, $formFactory, $userManager, $tokenStorage);
}
/**
* #Route("/register", name="register")
*/
public function registerAction(Request $request)
{
//do your stuff
}
}
hope this help (sorry for bad english)

To solve this issue in an override:
Do a full override of the FOSUserBundle RegistrationController i.e. copy its entire contents to AppBundle/Controller/RegistrationController.php
Then replace the __construct function with the below:
public function __construct() {
$this->eventDispatcher = $this->get('event_dispatcher');
$this->formFactory = $this->get('fos_user.registration.form.factory');
$this->userManager = $this->get('fos_user.user_manager');
$this->tokenStorage = $this->get('security.token_storage'); }
Voila! You are just calling these services in the constructor instead of passing them in as parameters in a registration controller service.
I did this now & it works for sf3.4.

I had the same problem , with SF4, FOSUserBundle (behind SonataAdmin).
I wanted listen an event : Registration confirmed, to send a message to the admininstrator.
my first try : override the FosUser controller. But the issues are many !
Thanks to #majne, I went to http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html, and, even I am not in 'master', that works, hooking the event, from FOS\UserBundle\FOSUserEvents class.
I had some problems to cleary adapt the use statements...

With Symfony 4.2 the following should work.
Contrary to what is suggested in other answers, there was no need to extend the corresponding FOSUserBundle controller or modify the __construct method.
/config/services.yaml
FOS\UserBundle\Form\Factory\FactoryInterface: '#fos_user.registration.form.factory'
In my case I actually overrode both the RegistrationController and the ResettingController and in that case one needs to wire both forms - and also the MailerInterface - as so:
/config/services.yaml
FOS\UserBundle\Form\Factory\FactoryInterface: '#fos_user.resetting.form.factory'
FOS\UserBundle\Mailer\MailerInterface: '#fos_user.mailer.default'
App\Controller\RegistrationController:
autowire: true
arguments:
$formFactory: '#fos_user.registration.form.factory'

I had the same problem and I solve it by making "fos_user.resetting.form.factory" public
#fos_user.yaml
services:
new_service_name:
alias: fos_user.registration.form.factory
public: true
Then use the service with the new name
$form = $this->get('new_service_name');

Related

Symfony Flex: Overriding Twig's routing path function

In Symfony2 it was straightforward to override the RoutingExtension, that I could inject some extra parameters.
I'm using a dynamic domain to route to different parts of my application.
{subdomain}.domain.com
However, I don't want to have to specify subdomain every time I call path or url in twig.
I could create my own unique filter name, but I'd rather not.
Previously, we could put this in the services.yaml file and it would work.
services:
twig.extension.routing:
class: AppBundle\Twig\Extension\RoutingExtension
public: false
arguments:
- '#router'
- '#request_stack'
- '%domain%'
Symfony2 Twig overriding default path function
With Symfony Flex, all I get is Unable to register extension "App\TwigExtension\TwigRoutingExtension" as it is already registered.
This is how to override Twig's routing path/url functions in Symfony 5.x using AbstractExtension:
namespace App\Twig;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class MyRoutingExtension extends AbstractExtension
{
public function __construct(
private UrlGeneratorInterface $generator
){}
public function getFunctions(): array
{
return [
new TwigFunction('path', [$this, 'getPath']),
new TwigFunction('url', [$this, 'getUrl']),
];
}
public function getPath(string $name, array $parameters = [], bool $relative = false): string
{
return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
public function getUrl(string $name, array $parameters = [], bool $schemeRelative = false): string
{
return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
}
}
In SF4 it's even simpler:
first composer require symfony/twig-bundle twig/extensions
Normally autowiring is enable so you can simply do:
<?php
namespace App\Twig;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class TestExtension extends RoutingExtension
{
public function __construct(UrlGeneratorInterface $generator)
{
parent::__construct($generator);
}
public function getPath($name, $parameters = array(), $relative = false)
{
return parent::getPath($name, $parameters, $relative);
}
}
If you want to setup a service forget about arguments definition it's boring :). Assuming your %domain% is available in your parameter do something like this:
<?php
namespace App\Twig;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
class TestExtension extends RoutingExtension
{
/** #var RouterInterface $router */
protected $router;
/** #var RequestStack $stack */
protected $stack;
/** #var mixed $domain */
protected $domain;
/**
* TestExtension constructor.
*
* #param RouterInterface $router
* #param RequestStack $stack
* #param ParameterBagInterface $bag
*/
public function __construct(RouterInterface $router, RequestStack $stack, ParameterBagInterface $bag)
{
$this->router = $router;
$this->stack = $stack;
$this->domain = $bag->get('domain');
}
public function getPath($name, $parameters = array(), $relative = false)
{
return parent::getPath($name, $parameters, $relative);
}
}

Symfony: How to save each successful login to database table

i am developing a symfony restful api with tools like
FosRestBundle, FosUserBundle and Lexik JWT for api authentication.
I need to save each successful login in my app. So i created a Login entity
(user_id,loginDate) , but i don't know how to use it because the login in handled from Lexik.
Does anyone know how can i do this?
Thanks
You can use security.interactive_login event for that. More information can be found from the official documentation:
https://symfony.com/doc/current/components/security/authentication.html#authentication-events
Create the listener and register it:
namespace App\EventListener;
use App\Component\EntityManagerAwareTrait;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* #package App\EventListener
*/
class SecuritySubscriber implements EventSubscriberInterface
{
/**
* #param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* #return array
*/
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User) {
$user->setLoginDate(new \DateTime());
$this->em->persist($user);
$this->em->flush();
}
}
}

FOSUserBundle: Registration redirect if logged in

I was wondering what would be the best method to redirect a user who is ALREADY LOGGED IN if they try and access the registration page.
I would prefer a method that does not require me overriding the registration controller simply to implement a login check & redirect.
I looked at the registration initialization event but I don't know how to initiate the redirect since there doesn't seem to be a way to set the event response via the UserEvent class.
Thanks
I use something like the following..
namespace Acme\UserBundle\EventSubscriber;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
class FOSUserSubscriber implements EventSubscriberInterface
{
protected $router;
protected $securityContext;
public function __construct(
UrlGeneratorInterface $router,
SecurityContextInterface $securityContext
)
{
$this->router = $router;
$this->securityContext = $securityContext;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'forwardToRouteIfUser',
);
}
public function forwardToRouteIfUser(GetResponseUserEvent $event)
{
if (!$this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return;
}
$url = $this->router->generate('acme_the_route_to_redirect_to');
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
With
parameters:
acme_user.subscriber.fos_user.class:
Acme\UserBundle\EventSubscriber\FOSUserSubscriber
services:
acme_user.subscriber.fos_user:
class: %acme_user.subscriber.fos_user.class%
arguments:
- #router
- #security.context
tags:
- { name: kernel.event_subscriber

Symfony2: check-email after registration

First time I'm posting a message in this forum, which I use regularly. I use FOSUserbundle in my Symfony2 application to manage users. I activated the sending of the email confirmation when users create an account by the following thing:
fos_user:
registration:
confirmation:
enabled: true
It works very well: the email is sent successfully. I am redirected to the page /check-email that says that this email has been sent. However, I would like to change the redirection : I would like to be redirected to my index page and not to /check-email. So I did my research and I knew he had to go through the FOSUserBundle events (list here).
What I did :
class RegistrationListener implements EventSubscriberInterface {
private $router;
public function __construct(UrlGeneratorInterface $router) {
$this->router = $router;
}
public static function getSubscribedEvents() {
return array(
FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm');
}
public function onRegistrationConfirm(FormEvent $event) {
$url = $this->router->generate('listeArticlesAccueil');
$event->setResponse(new RedirectResponse($url));
}
}
and services.yml
services:
listener_user.registration_listener:
class: My\Soft\UserBundle\EventListener\RegistrationListener
arguments: [#router]
tags:
- { name: kernel.event_subscriber }
The problem is that every time I am redirected to the page /check-email. I therefore told me that it was probably the wrong event. So I also tried REGISTRATION_SUCCESS. But nothing changes. So either I have not used the right event, or I'm doing something wrong.
In either case, I hope you can help me !
Thanks a lot and sorry for my bad english ;)
I know that this question has been posted a long time ago, but i found a solution and I would like to share it to others that have the same issue.
In this case, the event that you should use is REGISTRATION_SUCCESS.
You have to prioritize the listener REGISTRATION_SUCCESS to be called before FOS\UserBundle\EventListener\EmailConfirmationListener::onRegistrationSuccess like this:
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_SUCCESS => [
['onRegistrationSuccess', -10],
],
];
}
If you don't do it, EmailConfirmationListener will be called earlier and you will be redirected to fos_user_registration_check_email route.
Here is what I did:
class RedirectAfterRegistrationSubscriber implements EventSubscriberInterface
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onRegistrationSuccess(FormEvent $event)
{
$event->stopPropagation();
$url = $this->router->generate('homepage');
$response = new RedirectResponse($url);
$event->setResponse($response);
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::REGISTRATION_SUCCESS => ['onRegistrationSuccess',-10],
];
}
}
And in app/services.yml:
app.redirect_after_registration_subscriber:
class: AppBundle\EventListener\RedirectAfterRegistrationSubscriber
arguments: ['#router']
tags:
- { name: kernel.event_subscriber }
I hope this helps.
I would bet on REGISTRATION_SUCCESS.
The doc (https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/FOSUserEvents.php) says
that this event allows to set the response.
REGISTRATION_CONFIRM only allows to access the user
Instead of that use REGISTRATION_CONFIRM.
Here is the complete code for the event listener:
/**
* Description of RegisterationConfirmListener
*
* #author imran
*/
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\GetResponseUserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Description of RegisterationConfirmListener
*
* #author imran
*/
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\GetResponseUserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Listener responsible to change the redirection at the end of the password resetting
*/
class RegisterationConfirmListener implements EventSubscriberInterface {
private $router;
public function __construct(UrlGeneratorInterface $router) {
$this->router = $router;
}
public static function getSubscribedEvents() {
return [
FOSUserEvents::REGISTRATION_CONFIRM => 'onRegisterationConfirm',
];
}
public function onRegisterationConfirm(GetResponseUserEvent $event) {
$url = $this->router->generate('home');
$event->setResponse(new RedirectResponse($url));
}
}
For Services.yml:
app_user.registeration_confirmed:
class: Wishlocker\AppBundle\EventListener\RegisterationConfirmListener
arguments: [ #router ]
tags:
- { name: kernel.event_subscriber }

Add a default role during user registration with FOSUserBundle

Version : Symfony 2.2
I'm trying to add a default role when a user register on my website. I use FOSUserBundle and i see that when a user register the role field is empty in a database.
I begin with this huge bundle and it's not very easy to understand. So i read all the documentation and i'm not sur what to do.
For now, i create an Event to add this role dynamically, but it doesn't work (i have no error but my database is still empty) I'm not even sur this is the good way to do that ?
My Event :
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AddDefaultRoleListener implements EventSubscriberInterface {
private $container;
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onAddDefaultRoleSuccess',
);
}
public function onAddDefaultRoleSuccess(FormEvent $event)
{
$doctrine = $this->container->get('doctrine');
$em = $doctrine->getManager();
$user = $event->getForm()->getData();
$user->addRole('ROLE_USER');
//$user->setRoles(array('ROLE_USER'));
$em->persist($user);
}
}
As you see i create a simple event which listen on REGISTRATION_SUCCESS, but nothing seems to work. It's my first try with Events and services. So if someone has an advice, i'll take it :)
The recommended way to do it as indicated by a main contributor to the FOSUserBundle (in the comment here linked) is to register an Event Listener on the REGISTRATION_SUCCESS event and use the $event->getForm()->getData() to access the user and modify it.
Following those guidelines, I created the following listener (which works!):
<?php
// src/Acme/DemoBundle/EventListener/RegistrationListener.php
namespace Acme\DemoBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener responsible for adding the default user role at registration
*/
class RegistrationListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
);
}
public function onRegistrationSuccess(FormEvent $event)
{
$rolesArr = array('ROLE_USER');
/** #var $user \FOS\UserBundle\Model\UserInterface */
$user = $event->getForm()->getData();
$user->setRoles($rolesArr);
}
}
Also, the service needs to be registered as follows:
// src/Acme/DemoBundle/Resources/config/services.yml
services:
demo_user.registration_listener:
class: Acme\DemoBundle\EventListener\RegistrationListener
arguments: []
tags:
- { name: kernel.event_subscriber }
Notice that adding a default role in the User class __construct() may have some issues as indicated in this other answer.
What i have done is override the entity constructor:
Here a piece of my Entity/User.php
public function __construct()
{
parent::__construct();
// your own logic
$this->roles = array('ROLE_USER');
}
This is the lazy way. If you want the right and better way see the #RayOnAir answer
I think #RayOnAir solution is right way of doing this. But it will not work due to FOS default role handling
to make possible to persist default role in database one need to override User::setRoles() method (add it to your User entity):
/**
* Overriding Fos User class due to impossible to set default role ROLE_USER
* #see User at line 138
* #link https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Model/User.php#L138
* {#inheritdoc}
*/
public function addRole($role)
{
$role = strtoupper($role);
if (!in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
return $this;
}
Tested under:
Symfony version 2.3.6,
FOSUserBundle 2.0.x-dev
You can add an Event Subscriber to a Form Class and use the form event "formEvents::POST_SUBMIT"
<?php
//src/yourNS/UserBundle/Form/Type/RegistrationFormType.php
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use yourNS\UserBundle\Form\EventListener\AddRoleFieldSubscriber;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
// add your custom field
$builder->add('firstName')
->add('lastName')
->add('address')
//...
//...
->add('phone');
$builder->addEventSubscriber(new AddRoleFieldSubscriber());
}
public function getName()
{
return 'yourNS_user_registration';
}
}
Now the logic for adding the role field resides in it own subscriber class
<?php
//src/yourNS/UserBundle/Form/EventListener/AddRoleFieldSubscriber.php
namespace yourNS\UserBundle\Form\EventListener;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AddRoleFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(FormEvents::POST_SUBMIT => 'setRole');
}
public function setRole(FormEvent $event)
{
$aRoles = array('ROLE_USER');
/** #var $user \FOS\UserBundle\Model\UserInterface */
$user = $event->getForm()->getData();
$user->setRoles($aRoles);
}
}
Ok now it's working with that :
public function onAddDefaultRoleSuccess(FilterUserResponseEvent $event)
{
$doctrine = $this->container->get('doctrine');
$em = $doctrine->getManager();
$user = $event->getUser();
$user->addRole('ROLE_BLOGGER');
$em->persist($user);
$em->flush();
}
I change my listener and know use REGISTRATION_COMPLETED. If someone has a better idea to do that, don't hesitate :)
public function __construct()
{
parent::__construct();
$this->setRoles(["ROLE_WHATEVER"]);
}

Resources