How to assign role with PHP in Drupal?(如何在 Drupal 中使用 PHP 分配角色?)
问题描述
我需要为通过 PHP 购买金额等于或大于 100 欧元的会员分配一种高级状态".
I need to assign a kind of "premium status" to members that purchase an amount equal or greater than 100 € via PHP.
条件操作已经设置(用户 = 匿名/经过身份验证 AND 总金额 = 等于/大于 100 AND 用户 =!溢价)但我缺少 PHP 部分来实际说然后授予他高级会员资格".
Conditional Actions are already set up (user = anonymous/authenticated AND total amount = equal/greater than 100 AND user =! premium) but I'm missing the PHP part to actually say "then grant him the premium membership".
我怎样才能做到这一点?
How can I achieve this?
下面的代码正确吗?
if ($account) {
$uid = $account->uid;
$role_name = 'authenticated user';
$rid = db_result(db_query("SELECT rid FROM {role} WHERE name = '%s'", $role_name));
db_query("INSERT INTO {users_roles} (uid, rid) VALUES(%d, %d)", $uid, $rid);
watchdog('user', 'uc ca added role to Ubercart created user');
}
推荐答案
你可以用 user_load()
和 user_save()
:
$uid = 1; // UID of user to add role to
$role_name = 'test role'; // Name of role to add
// Get RID of role
$rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name));
// Load user object
$account = user_load(array('uid' => 1));
// Save the user object with the new roles.
if ($account !== FALSE && !isset($account->roles[$rid])) {
$roles = $account->roles + array($rid => $role_name);
user_save($account, array('roles' => $roles));
}
如果您想为多个用户批量执行此操作,请使用 user_multiple_role_edit()
:
If you wanted to do this in bulk for multiple users, there's user_multiple_role_edit()
:
$uids = array(1, 2, 3, 4); // UIDs of users to add role to
$role_name = 'test role'; // Name of role to add
// Get RID of role
$rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name));
// Add the role to UIDs
user_multiple_role_edit($uids, 'add_role', $rid);
<小时>
编辑
如果您想为当前用户执行此操作(例如您在评论中提到的检查的一部分),您可以执行以下操作:
Edit
If you wanted to do this for the current user (like part of the check you mentioned in a comment), you can do:
// Check for value over 100.00
if ($total_value > 100) {
global $user; // Retrieve user object for currently logged in user.
$role_name = 'test role'; // Name of role to add
// Get RID of role
$rid = db_result(db_query("SELECT r.rid FROM {role} r WHERE r.name = '%s'", $role_name));
// Save the user object with the new role.
if (!isset($user->roles[$rid])) {
$roles = $user->roles + array($rid => $role_name);
user_save($user, array('roles' => $roles));
}
}
// Other code here.
这篇关于如何在 Drupal 中使用 PHP 分配角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Drupal 中使用 PHP 分配角色?
基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01