I'm using Symfony 2.1 for a project. I use the FOSUserBundle for managing users & SonataAdminBundle for administration usage.
I have some questions about that:
As an admin, I want to set roles from users in users edit form. How can I have access to roles in role_hierarchy
? And how can I use them as choice fields so the admin can set roles to users?
When I show roles in a list, it is shown as string like this:
[0 => ROLE_SUPER_ADMIN] [1 => ROLE_USER]
How can I change it to this?
ROLE_SUPER_ADMIN, ROLE_USER
I mean, having just the value of the array.
Based on the answer of @parisssss although it was wrong, here is a working solution. The Sonata input field will show all the roles that are under the given role if you save one role.
On the other hand, in the database will be stored only the most important role. But that makes absolute sense in the Sf way.
protected function configureFormFields(FormMapper $formMapper) {
// ..
$container = $this->getConfigurationPool()->getContainer();
$roles = $container->getParameter('security.role_hierarchy.roles');
$rolesChoices = self::flattenRoles($roles);
$formMapper
//...
->add('roles', 'choice', array(
'choices' => $rolesChoices,
'multiple' => true
)
);
And in another method:
/**
* Turns the role's array keys into string <ROLES_NAME> keys.
* @todo Move to convenience or make it recursive ? ;-)
*/
protected static function flattenRoles($rolesHierarchy)
{
$flatRoles = array();
foreach($rolesHierarchy as $roles) {
if(empty($roles)) {
continue;
}
foreach($roles as $role) {
if(!isset($flatRoles[$role])) {
$flatRoles[$role] = $role;
}
}
}
return $flatRoles;
}
See it in action: