I am using SonataAdminBundle for user administration. I would like to change roles on users. Currently my code in configureFormFields method is like this but roles are never updated and I don't know why.
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('roles', 'choice', array(
'choices' => array(
'ROLE_ADMIN' => 'ADMIN',
'ROLE_USER' => 'API USER',
),
'expanded' => false,
'multiple' => true,
'required' => false
))
->add('email')
->add('plainPassword', 'text', array('label' => 'Password', 'required' => false))
->end()
;
}
FOSUserBundle supports having multiple ROLES per user which is fine thing indeed. In my experience however, a common use case is a single role per user.
An easy way to manage this is to add the following method to your model/entity object to obtain a single role:
public function getRole() {
$role = $this->roles[0];
return $role;
}
Note: $role = $this->roles[0]
will return the first ROLE in the database roles field. It may be that you need to choose the correct role with your own logic. Or, it may also be that you need to get the default role. If you use $this->getRoles()
instead of $this->roles
you have have the database roles plus the default role in the returned array.
Next you need to add a matching setter to allow you to save the single role per user. This implementation will work.
public function setRole($role) {
$this->setRoles(array($role));
}
Finally you will want to add a role field in your user form:
$builder->add('role', 'choice', array(
'choices' => array(
'ROLE_USER' => 'User',
'ROLE_ADMIN' => 'Admin',
'ROLE_SUPER_ADMIN' => 'Super Admin'
),
'multiple' => false
));
An important thing to note:
$builder->add('role'...
: 'role'
NOT 'roles'