Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal: assign roles in user_save

I can't find a solution or right example for something that should be quite simple: assign a role to an user when creating it, this is what I'm trying:

$edit = array(
        'name' => $_POST['name'],
        'pass' => $password,
        'mail' => $_POST['email'],
        'status' => 0,
        'language' => 'es',
        'init' => $_POST['email'],
        array(2 =>'authenticated', 4=>'my custom role') //as id and named in role db table
      );

user_save(NULL, $edit);

The user is not being created, how can I do this?

Thank you

like image 485
K. Weber Avatar asked Jun 28 '12 08:06

K. Weber


2 Answers

You haven't named the roles member as such. Try his modified version:

$edit = array(
  'name' => $_POST['name'],
  'pass' => $password,
  'mail' => $_POST['email'],
  'status' => 0,
  'language' => 'es',
  'init' => $_POST['email'],
  'roles' => array(
    2 => 'authenticated',
    4 => 'my custom role',
  ),
);

user_save(NULL, $edit);
like image 121
Tobias Sjösten Avatar answered Oct 17 '22 05:10

Tobias Sjösten


And you can use objects to do that.

// Check if user's email is unique
if (!user_load_by_mail($_POST['email'])) {
  $account = new stdClass;
  $account->name = $_POST['name'];
  $account->pass = user_hash_password($password);
  $account->mail = $_POST['email'];
  $account->status = FALSE;
  $account->language = 'es';
  $account->init = $_POST['email'];
  $account->roles = array(
    DRUPAL_AUTHENTICATED_RID => TRUE,
    'Your custom role' => TRUE,
  );
  user_save($account);
}
like image 22
Juuuuuu Avatar answered Oct 17 '22 06:10

Juuuuuu