1

I know that you can create user programtically and set a role:

 $roles = array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      4 => 'Member');
$fields = array(
    'name' => $username,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => $email,
    'roles' => $roles,
    );
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);    

and this code works fine. However, I am going to be porting this code to different sites (and back to mine, when I need to do testing on my dev site), and I'm trying to figure out if I'm going to have role id conflicts. Instead of using the above code, and I do the following instead?

$roles = array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      "site-member" => 'Member');

and thereby never having to worry that I am overwriting a role?

1

One way can be to get role id from role name than use role, since we fetch the rid dynamically so there is no chance of conflict. An example will go like

// Helper function to get user role by username.
function get_role_by_name($name) {
  $roles = user_roles();
  return array_search($name, $roles);
}

// Role ID for Member role
$member_rid =  get_role_by_name("Member");

// Use Rid now
$roles = array(
$member_rid => 'Member');

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.