Symfony: FOS user Bundle promotes user through controller

I'm new to bundling with FOS. I have a user and want to create a function to promote them (which will do the same as:

php app/console fos:user:promote testuser ROLE_MANAGER 

      

my security.yml:

role_hierarchy:
    ROLE_MANAGER:       ROLE_USER
    ROLE_ADMIN:         [ROLE_USER, ROLE_MANAGER, ROLE_ALLOWED_TO_SWITCH]

      

Any idea how to do this from a controller? I created a UserBundle with UserController.php to extend the FOS user and create a profile.

+3


source to share


2 answers


Found a solution:

public function promoteUserAction(){

    $user = $this->getUser();

    $userManager = $this->get('fos_user.user_manager');    
    $user->addRole('ROLE_ADMIN');
    $userManager->updateUser($user);

    return $this->render('ACMEBundle:User:page.html.twig');
} 

      



Hope it will be helpful to others. greetings

+6


source


Also, if you only know the FOS username and want the user to register as a different user (the accepted answer promotes a registered user), you can use this example code:

$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('username' => 'gauss'));
$user->addRole('ROLE_ADMIN');
$userManager->updateUser($user);

      



In this case, I am looking for the FOS username for "gauss" and contribute to using gauss for ROLE_ADMIN. Then you can run sql command select id,username,roles from fos_user;

on your database to check that the role has been added.

Hope this helps someone.

+2


source







All Articles