Drupal: assign roles in user_save

2019-04-08 10:57发布

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

4条回答
叛逆
2楼-- · 2019-04-08 11:37
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);
  } 
}
查看更多
对你真心纯属浪费
3楼-- · 2019-04-08 11:45

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);
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-08 11:49

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);
查看更多
唯我独甜
5楼-- · 2019-04-08 11:50

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.

查看更多
登录 后发表回答