5

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

K. Weber
  • 2,643
  • 5
  • 45
  • 77

4 Answers4

12

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);
Tobias Sjösten
  • 1,084
  • 9
  • 16
5

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);
}
Juuuuuu
  • 135
  • 11
0

Here is a hook I've written to add a role to a user when a new user is inserted:

<?php
function MYMODULE_user_insert(&$edit, $account, $category){
  if (array_key_exists('profile_1', $account)) {
    $is_university = FALSE;
    if ($account->profile_sport_club['field_club']['und'][0]['value'] == 1 ) {
      $is_university = TRUE;
    }
    if ($is_university) {
      $uid = $account->uid;
      $role_name = 'uni_club';
      if ($role = user_role_load_by_name($role_name)) {
        user_multiple_role_edit(array($uid), 'add_role', $role->rid);
      }
    }
  }
} 
?>

Thanks to this tip, it's now much simpler.

Druvision
  • 1,463
  • 1
  • 15
  • 16
0
function first_user_insert(&$edit, $account, $category, $node){
  $uid = $account->uid;
  $role_name = 'role name';
  if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($uid), 'add_role', $role->rid);
  } 
}
  • 1
    While this code may serve to answer the question it would help if commentary was added that describes exactly what the code does and how it should be integrated with the code in the question. This will help others in the future who come across this question and answer. – Bruce P Nov 08 '15 at 15:40