It looks pretty simple and I'm a begginer with Symfony, but couldn't figure it out.
I'm using FOSUserBundle, and I'm trying to add a specific role (ROLE_ADMIN) to a specific user (e.g. me), so when the user logs in that role is assigned and he can access certain pages.
I tried putting something like this in the __construct()
method of my User entity, but it didn't work:
if($this->getUsername()=='johndoe') $this->addRole('ROLE_ADMIN');
When I log in as that user, the debugging utilities show only the 'ROLE_USER', os it is not working.
Is that a right code? Where should I put it?
Update:
There was a silly error that accidentally found. I had created the User entity before isntalling FOSUserBundle, and somehow the user I was trying to promote gave me errors through CLI. Maybe it wasn't properly stored in the database. Once I created a new one and tried again, the command worked as expected.
To assign a user to a user role In the Edit User Role dialog box, click Users. On the Users page, click Add. In the Select Users or Groups dialog box, type the name of a user or group that you want to add to this user role, click Check Names, and then click OK. In the Edit User Role dialog box, click OK.
Assign roles in user profile Go to Dashboard > User Management > Users and click the name of the user. Click the Roles view, and click Assign Role. Choose the role you wish to assign and click Assign.
In case you can access the database, just update the roles
column:
["ROLE_ADMIN"]
try this
$userObject=$this->getUser();
$username = $userObject->getUsername();
if($username == 'johndoe')
{
$user = $this->get('fos_user.user_manager')->findUserByUsernameOrEmail($username);
$user->setRoles( array('ROLE_ADMIN') );
$userManager->updateUser($user, true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With