Drupal:在user_save中分配角色

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个回答

12

你没有将roles成员命名为这样。试试他修改后的版本:

$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
你可以使用对象来实现这一点。
// 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);
}

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
虽然这段代码可能可以回答问题,但如果添加描述代码功能和如何与问题中的代码集成的评论将会更有帮助。这将有助于未来遇到此问题和答案的其他人。 - Bruce P

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

多亏了这个提示, 现在变得更简单了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接