In FOSUserBundle, How to initially set user role on REGISTRATION_COMPLETED event?
events, fosuserbundle, php, symfony
Solution
Have you tried calling `addRole()` FOSUser entity function,if you notice the setRole function in entity it is looping through the array to roles and passing it to `addRole`
public function setRoles(array $roles)
{
$this->roles = array();
foreach ($roles as $role) {
$this->addRole($role);
}
return $this;
}
Try with `addRole()` for single role
public function onRegistrationSuccess(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->addRole('ROLE_USER');
$this->um->updateUser($user);
$this->dm->flush();
}
Problem
I'm trying to give each successfully registered user a `ROLE_USER` role. I'm new to FOSUserBundle, So from what I've read in the documentation, It's done by hocking logic into the controllers. Here's my `NewUserGroupSet` Event listener: ``` <?php namespace Tsk\TstBundle\EventListener; use Doctrine\ODM\MongoDB\DocumentManager; use FOS\UserBundle\Doctrine\UserManager; use FOS\UserBundle\Event\FilterUserResponseEvent; use FOS\UserBundle\FOSUserEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class NewUserGroupSet implements EventSubscriberInterface { protected $um; protected $dm; public function __construct(UserManager $um, DocumentManager $dm) { $this->um = $um; $this->dm = $dm; } public static function getSubscribedEvents() { return array( FOSUserEvents::REGISTRATION_COMPLETED => "onRegistrationSuccess", ); } public function onRegistrationSuccess(FilterUserResponseEvent $event) { $user = $event->getUser(); $user->setRoles(array('ROLE_USER')); $this->um->updateUser($user); $this->dm->flush(); } } ?> ``` And is registered as a service as follows: ``` parameters: tsk_user.group_set.class: Tsk\TstBundle\EventListener\NewUserGroupSet services: tsk_user.group_set: class: %tsk_user.group_set.class% arguments: [@fos_user.user_manager, @doctrine.odm.mongodb.document_manager] tags: - { name: kernel.event_subscriber } ``` But when I register a new user, Nothing happens. No roles is being set whatsoever. Any help would be appreciated.