2

I have custom module code that check the user role and based on user role, user fields updated,

for example

if(array_key_exists(12,$user->roles)) {
    //Manger
    $role =  array(8=>8);
} elseif (array_key_exists(13,$user->roles) ) {
    // super Manger
    $role =  array(14=>14);
} elseif (array_key_exists(11,$user->roles)) {
    //section manager 
    $role =  array(14=>14,8=>8);
}

so when I want to move this module to other site and import roles using feature, the ids will changed.

so how can I use machine name for roles instead of ids.

Regard,

  • 1
  • 1
    I don't want to use role name because it might be changed, also there is different between role name and machine name. – drpl Feb 7 '15 at 11:57
  • If you have a look at the role table in the database you'll see that roles only have one name property. So the system name and human readable name are always the same. – Neograph734 Feb 7 '15 at 12:06
  • 1
    yes, so I asked this question so maybe found other way to avoid using role name and role id. – drpl Feb 7 '15 at 13:09
1

just make sure when you move your roles that you spell them the same! then you can use the traditional

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}

or the more flamboyant

function user_has_role($roles) {
    //checks if user has role/roles
    return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
};

if (user_has_role(array('moderator', 'administrator'))) {
  // $user is admin or moderator
}

see here for more answers to the simple question Check if a user has a role

  • This is a good approach as roles are hard due to the RID being used for so many things but the RID is an auto increment field. In D8 they have went away from RIDs but it still isn't easy. – Brady Feb 8 '15 at 22:38

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.