5

对于应该非常简单的事情,我找不到解决方案或正确示例:在创建用户时为其分配角色,这就是我正在尝试的:

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

没有创建用户,我该怎么做?

谢谢

4

4 回答 4

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);
于 2012-06-28T08:43:37.080 回答
5

你可以使用对象来做到这一点。

// 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);
}
于 2012-06-28T09:20:19.903 回答
0

这是我编写的一个钩子,用于在插入新用户时向用户添加角色:

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

多亏了这个技巧,它现在变得简单多了。

于 2013-10-23T15:07:53.737 回答
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);
  } 
}
于 2015-11-06T10:25:53.083 回答