当前登录的用户角色


18

如何在Drupal 8中获取当前登录的用户角色?

例如在D7中 $GLOBALS['user']->roles;

Answers:


31

就像是:

$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();

将返回一个数组,如:

Array
(
  [0] => authenticated
  [1] => administrator
  [2] => some_other_role
)

其中,数组值是角色ID(等同于Drupal 7中角色的计算机名称)。在OO代码中,使用适当的机制从容器中获取当前用户,例如

$current_user = $container->get('current_user');

好的答案,您可以添加代码$container吗?
学生

@Pupil为了访问容器在OO环境下,你应该创建类和使用依赖注入来调用它,如下所示例如drupal.org/docs/8/api/services-and-dependency-injection/...
wranvaud

0

要获得Drupal 8中的当前用户角色,请-

$role = \Drupal::currentUser()->getRoles();
foreach ($role as $value) {
   $role = $value;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.