2

I need to get permissions for all user roles, which are used. The code looks something like this:

$anonymous = Role::load('anonymous');
$anonymousPermissions = $anonymous->getPermissions();

The code for anonymous (and also for authenticated) returns an array of permissions, but the same code for administrator returns null:

$administrator = Role::load('administrator');

How can I get permissions for the role Administrator? (The machine name of role Administrator is administrator and also in the database is nothing suspicious.)


I have tried also:

$administratorPermissions = user_role_permissions(['administrator']);

It returns:

array(1) {
    ["administrator"] =>
        array(0) {
    }
}

If I try:

$roles = Role::loadMultiple();
foreach ($roles as $role => $rolesObj) {
    $role_list[$role] = $rolesObj->get('label');
}
print_r($role_list);

Then I get:

Array
(
    [anonymous] => Anonymous user
    [authenticated] => Authenticated user
)
5

See the Role::getPermissions() method code:

  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

So, if the user has all permissions the returned value is an empty array.

Why? I really don't know and I can't find the answer, maybe other user knows Why Role::getPermissions() method return an empty array for admin users?.

The good news is that you can get all the Administrator permission with this code:

array_keys(\Drupal::service('user.permissions')->getPermissions());

Test this code (You'll need the Devel module to use dpm()):

$administrator = Role::load('administrator');
if($administrator->isAdmin()) {
  dpm(array_keys(\Drupal::service('user.permissions')->getPermissions()));
}  
  • Thank you! It is a good solution and it works perfectly. – Antonín Slejška Apr 7 '17 at 7:49
  • @AntonínSlejška you're welcome, and good luck with your project ;-) – Adrian Cid Almaguer Apr 7 '17 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.