【问题标题】:Drupal: assign roles in user_saveDrupal:在 user_save 中分配角色
【发布时间】:2012-06-29 17:37:27
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: drupal drupal-7 roles


    【解决方案1】:
    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);
      } 
    }
    

    【讨论】:

    • 虽然此代码可能有助于回答问题,但如果添加注释以准确描述代码的作用以及应如何与问题中的代码集成,则会有所帮助。这将有助于将来遇到此问题和答案的其他人。
    【解决方案2】:

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

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

    感谢this tip,现在变得简单多了。

    【讨论】:

      【解决方案3】:

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

      // 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】:

        您还没有这样命名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);
        

        【讨论】:

          猜你喜欢
          • 2011-04-01
          • 1970-01-01
          • 2013-09-11
          • 1970-01-01
          • 2020-05-30
          • 2014-05-11
          • 1970-01-01
          • 2019-02-08
          • 1970-01-01
          相关资源
          最近更新 更多