Add User Role

Public

Short

Get raw version
php
  1. $role = user_role_load_by_name('Role-name');
  2. user_save($account, array('roles' => $account->roles + array($role->rid => $role->name)));

https://www.drupal.org/node/28379#comment-4277052

Get raw version
php
  1. $user_role = new stdClass();
  2. $user_role->name = 'vtiger portal user';
  3. $user_role->weight = 2;
  4. // save the role to the Drupal database
  5. user_role_save($user_role);
  6.  
  7. global $user;
  8. $key = array_search('your role', $user->roles);
  9. if ($key == FALSE) {
  10. $roles = user_roles(TRUE);
  11. $rid = array_search('your role', $roles);
  12. if ($rid != FALSE) {
  13. $new_role[$rid] = 'your role';
  14. user_save($user, array('roles' => $new_role));
  15. }
  16. }

https://www.drupal.org/node/28379#comment-4277052

Get raw version
php
  1. function morroni_add_role(&$user, $role_name) {
  2. $success = false;
  3. // jwatson load roles and get key of our desired role (if it exists)
  4. $roles = user_roles();
  5. $key = ($k = array_search($role_name, $roles)) > 0 ? $k : 0;
  6. if ($k > 0) {
  7. // add role to existing roles
  8. $user->roles[$key] = $role_name;
  9. // build array for user_save data
  10. $array = array('roles' => $user->roles);
  11. // save
  12. user_save($user, $array);
  13. $success = true;
  14. }
  15. return $success;
  16. }
  17.  
  18.  
  19. //usage
  20. $user = user_load(3);
  21. $result = (bool) morroni_add_role(&$user, 'role_name_goes_here');

Code Karate

Get raw version
php
  1. //you will need to enter the uid of the user here, I am just using user 1
  2. $user = user_load(1);
  3.  
  4. //first we check if the user has the role in question (using the rid of the role)
  5. if (!isset($user->roles[7])) {
  6. //if not we add the role and set the role name based on what is entered
  7. //in the drupal role administration section
  8. $user->roles[7] = 'role name seven';
  9. }

Code Karate

Get raw version
php
  1.  
  2. $olduser->user_load($uid); //load the user account
  3. $rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name)); //get the role id for a role name
  4. if (!isset($olduser->roles[$rid])) { //check if role exists
  5. $olduser->roles[$rid] = $role_name; //add new role with all other roles
  6. $newrole['roles'] = json_decode(json_encode($olduser->roles), true);; //add new role with others as array
  7.  
  8. $old_new_user = user_save($olduser,$newrole); //save new user details with new roles
  9. return $old_new_user; //return new user
  10. }

https://www.computerminds.co.uk/articles/quick-tips-adding-role-user-dru...

Get raw version
php
  1. $uid = 123;// User ID of user that you want to add role to.
  2. $role_name = 'Role to add'; // The name of the role to add.
  3. if ($role = user_role_load_by_name($role_name)) {
  4. user_multiple_role_edit(array($uid), 'add_role', $role->rid);
  5. }