Drupal: assign roles in user_save

2019-04-08 11:16发布

问题:

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

回答1:

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);


回答2:

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);
}


回答3:

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.



回答4:

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);
  } 
}