phpdrupaldrupal-roles

How to assign a role programatically in Drupal 6? 'role' => 'rolename didn´t worked


I have this function to create a new user using the information that is inside a node form, in my Drupal 6 site:

function altas_create_user($name,$pass,$mail) {
  $newuser = array(
    'name' => $name,
    'mail' => $mail,
    'pass' => $pass,
    'access' => 1,
    'notify' => 1,
    'status' => 1,
  );
  return user_save(NULL, $newuser); 
}

Now, what I´ve noted is that I didn´t assign a role to that user. How may I do that?

I´ve tried adding this, that didn´t worked: 'role' => 'rolename',

How may I do that? Thanks for your help!

EDIT: I forgot to say that I´ve looked into the API, and found that maybe I should use 'roles' => $roles, but don´t understand how to actually fill $roles with my rolename.


Solution

  • Solved it! (found the answer here) and thought I would post it the results, just in case it helps someone: I should

    // Get an array of roles
    $roles = user_roles();
    

    first (inside the function, before $newuser array), and then,

    'roles' => array(array_search('myrolename', $roles) => 1),
    

    There, it works like a charm.