Changing a user object during registration using the FOS User Bundle and Symfony2

As many people know, the FOS User Bundle does not automatically provide a role when a user logs in. The most common solution is either: a) change the constructor of the user object to automatically assign the role, or b) redefine the entire registration controller.

None of these solutions seem perfect, and I want to use the events that the FOS package provides.

I managed to capture the event I want ( FOSUserEvents::REGISTRATION_INITIALIZE ), but it’s hard for me to figure out how to submit the modified user object back to the registration form.

The code I still have is as follows:

 namespace HCLabs\UserBundle\EventListener; use FOS\UserBundle\FOSUserEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\Model\UserInterface; class AutoRoleAssignmentListener implements EventSubscriberInterface { public static function getSubscribedEvents() { return [ FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInitialise' ]; } public function onRegistrationInitialise( UserEvent $event ) { $user = $event->getUser(); $user->addRole( 'ROLE_USER' ); // what do } } 

YML for event listener:

 services: hc_labs_user.reg_init: class: HCLabs\UserBundle\EventListener\AutoRoleAssignmentListener tags: - { name: kernel.event_subscriber } 

If more code is required, I am happy to provide it. Thank you for your help.

+6
source share
1 answer

The answer is very simple - you need to do nothing to update the User object in the registration form after updating the User in the event listener for the FOSUserEvents::REGISTRATION_INITIALIZE event.

Let me explain. FOSUserEvents::REGISTRATION_INITIALIZE sent to RegistrationController by:

 $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, new UserEvent($user, $request)); 

And before this submission, a new User is created in the code ( https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/RegistrationController.php#L43 ):

  $user = $userManager->createUser(); $user->setEnabled(true); $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, new UserEvent($user, $request)); 

When sending by default, PHP call_user_func ( http://php.net/manual/en/function.call-user-func.php ) is called with an embedded event name (function in a specific object) and an Event object. After that, the event listener has the ability to modify the attached Event object - especially the event property.

In your case, your event handler will change the User property with:

 $user = $event->getUser(); $user->addRole( 'ROLE_USER' ); 

Therefore, in fact, you do not need to do anything to submit the changed user object back to the registration form.

+8
source

Source: https://habr.com/ru/post/951656/


All Articles