Question

So, I've read through the documentation for the bundle, but there's nothing describing how to list existing roles or to assign/change rolls for a specific user. I need to be able to:

  1. Assign a default role to a newly registered user.
  2. Have admins and superadmins elevate and demote users.
    • This has a requirement of me being able to see what roles I can choose from.

So, how is this done?

Was it helpful?

Solution

You can do something like this:

$roleHierarchy = $container->getParameter('security.role_hierarchy.roles');
$roles = array_keys($roleHierarchy);
$form = $this->createForm(new UserFormType($roles, $user->getRoles()), $user);

In your UserFormType you can add the roles field like this:

protected $roles;
protected $userRoles;

public function __construct($roles, $userRoles)
{

    foreach ($roles as $role) {
        $theRoles[$role] = $role;
    }
    $this->roles = $theRoles;
    $this->userRoles = $userRoles;

}

public function buildForm(FormBuilderInterface $builder, array $options)
{               

    $builder->add('roles', 'choice', array(
                    'choices' => $this->roles,
                    'data' => $this->userRoles,
                    'expanded' => true,
                    'multiple' => true,
                ));

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top