0

I want to create a new role. New role should have all the permissions of authenticated user as well as the some new permissions.

I used the following code,

$role = new stdClass();
$role->name = 'New role';

// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
$role->weight = $auth_role->weight + 1;

user_role_save($role);

and I will assign the permissions using user_role_change_permissions() or user_role_grant_permissions()

Now I want to assign the authenticated user permissions to this new role. How to achieve this?

2 Answers 2

1

Got it. following code will achieve the this functionality,

$role = new stdClass();
$role->name = 'New role';
// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
// Give the weight more than authenticate user, so that
// New role will have all the authenticated user permissions
// by default.
$role->weight = $auth_role->weight + 1;
user_role_save($role);
$auth_permissions = user_role_permissions(array(DRUPAL_AUTHENTICATED_RID => 'authenticated users'));
$auth_permissions += array('other permissions');
// Grant permissions to our 'New role' role
user_role_grant_permissions($role->rid, array_keys($auth_permissions[DRUPAL_AUTHENTICATED_RID]));
1
  • The code didn't work for me, but changing the second $auth_permissions line to this fixed it: $auth_permissions[DRUPAL_AUTHENTICATED_RID] += array('other permissions' => 1);
    – Whiskey
    Sep 21, 2012 at 14:12
0

Here is code that will assign new role to user:

global $user;
$key = array_search('your role', $user->roles);
if ($key == FALSE) {
  $roles = user_roles(TRUE);
  $rid = array_search('your role', $roles);
  if ($rid != FALSE) {
    /* change role in current session*/  
    $user->roles[$rid] = 'your role';
    /*save role in db*/
    $new_role[$rid] = 'your role';
    user_save($user, array('roles' => $new_role));
  }
}
2
  • -1 This is not what I want. I'm talking about creating a new user role, not assigning a new role to the user. Jul 30, 2012 at 14:17
  • Your question sounds "Now I want to assign the authenticated user permissions to this new role. How to achieve this?" So i think you want assign this new role to user. Jul 30, 2012 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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