Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set role for users in edit form of sonata admin

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:

  1. 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?

  2. 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.

like image 974
parisssss Avatar asked Nov 27 '22 11:11

parisssss


2 Answers

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:

enter image description hereenter image description here

like image 153
Romain Bruckert Avatar answered Dec 05 '22 13:12

Romain Bruckert


As for the second question I added a method in the User class that looks like this

/**
 * @return string
 */
 public function getRolesAsString()
 {
     $roles = array();
     foreach ($this->getRoles() as $role) {
        $role = explode('_', $role);
        array_shift($role);
        $roles[] = ucfirst(strtolower(implode(' ', $role)));
     }

     return implode(', ', $roles);
 }

And then you can declare in your configureListFields function:

->add('rolesAsString', 'string')
like image 29
karolsojko Avatar answered Dec 05 '22 12:12

karolsojko