1

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

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

        }
    }
}

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

从昨天开始我一直在努力解决这个问题,所以非常欢迎任何帮助......

4

1 回答 1

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

}

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

希望能帮助到你

于 2013-03-12T16:17:33.947 回答