Drupal 6:无法以编程方式添加/撤消用户角色(触发器/操作模块)

时间:2013-03-11 23:57:01

标签: drupal drupal-6

我正在尝试使用触发器和自定义操作,在给定特定配置文件字段的情况下为用户(在添加/编辑时)提供特殊角色。所以这是我的代码:

function mymodule_action_info() {
    return array(
        'mymodule_user_appropriate_role' => array(
            'description' => t('Assign user special role'),
            'type' => 'user',
            'configurable' => FALSE,
            'hooks' => array(
                'user' => array('insert', 'update'),
            ),
        ),
    );
}

然后

function mymodule_user_appropriate_role(&$object, $context = array()) {
    // get the uid from the object
    if( isset( $object->uid ) ){
        $thisUID = $object->uid;
    }else if( isset( $context['uid'] ) ){
        $thisUID = $context['uid'];
    }else{
        global $user;
        $thisUID = $user->uid;
    }
    // make sure we have a user record
    if( $thisUID ){
        // load user object
        $thisUser = user_load( $thisUID );
        // get user profile object
        profile_load_profile( $thisUser );

        if( $thisUser->profile_special_field == "value1" ){

            // FIRST APPROACH
            db_query( 'INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $thisUser->uid, 5 ); // 5 is the custom role ID

            // SECOND APPROACH
            $thisUserRoles = $thisUser->roles;
            if( !isset( $thisUserRoles[5] ) ){
                $thisUserRoles[5] = "RID 5 Rule Name";
            }
            user_save( $thisUser, array( 'roles' => $thisUserRoles ) );

            // THIRD APPROACH
            $allUserRoles = user_roles();
            user_save( $thisUser, array( 'roles' => array( array_search( 'RID 5 Rule Name', $allUserRoles ) => 1 ) ) );

        }
    }
}

但这3种方法都没有奏效。我确定已调用该操作并输入if( $thisUser->profile_special_field == "value1" )语句

我从昨天开始就一直在努力,所以任何帮助都是最受欢迎的......

1 个答案:

答案 0 :(得分:0)

我最终得到了hook_user。以下是供参考的代码:

function mymodule_helper_user($op, &$edit, &$account, $category = NULL){

    // DEFINE OPERATIONS LIST TO ACT ON
    $opList = array( 'insert', 'update', 'after_update', 'submit' );

    if( in_array( $op, $opList ) ){

        // REVOKE ALL CUSTOM ROLES, HERE RID 5 AND 6
        db_query( 'DELETE FROM {users_roles} WHERE rid IN (5,6) AND uid = %d', $account->uid );

        if( $account->profile_custom_field == 'value1' ){
            // GIVE CUSTOM RID 5
            db_query( 'INSERT IGNORE INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, 5 );
        }else if( $account->profile_custom_field == 'value2' ){
            // GIVE CUSTOM RID 6
            db_query( 'INSERT IGNORE INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, 6 );
        }
    }

}

对于操作列表,在“更新”上执行此操作对我来说不起作用,而不是“after_update”,这就是为什么我添加了四个可疑的操作,直到我测试并保留了什么是需要

希望有所帮助