Token: List users who has a specific role

Public

Usage: [user:]

</> CopyGet raw version
php
  1. <?php
  2.  
  3. /**
  4.  * Implements hook_token_info().
  5.  */
  6. function MY_MODULE_token_info() {
  7. $info = [];
  8. $info['tokens']['user']['users-with-role'] = array(
  9. 'name' => t('Users with role'),
  10. 'description' => t('Get the name of the users who has the given role.'),
  11. 'dynamic' => TRUE,
  12. );
  13. return $info;
  14. }
  15.  
  16. /**
  17.  * Implements hook_tokens().
  18.  */
  19. function MY_MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  20. $return = [];
  21. if ($type == 'user') {
  22. foreach ($tokens as $name => $original) {
  23. if (strpos($name, 'users-with-role') !== FALSE) {
  24. list($token_name, $role) = explode(':', $name);
  25. $users = MY_MODULE_get_users_with_role($role);
  26. $user_names = array_map(function ($user) {
  27. return $user->name;
  28. }, $users);
  29. $return[$original] = implode(', ', $user_names);
  30. }
  31. }
  32. }
  33.  
  34. return $return;
  35. }
  36.  
  37. /**
  38.  * Return all users who have the given role.
  39.  *
  40.  * @param int|string $role
  41.  * Name of the role or the ID or the role.
  42.  * @param bool|TRUE $active_user
  43.  * Determine, if only the active users should be returned.
  44.  * @return array
  45.  * Array of user objects.
  46.  */
  47. function MY_MODULE_get_users_with_role($role, $active_user = TRUE) {
  48. $users = array();
  49. $rid = 0;
  50. if (is_int($role)) {
  51. $rid = $role;
  52. }
  53. else {
  54. if ($role_obj = user_role_load_by_name($role)) {
  55. $rid = $role_obj->rid;
  56. }
  57. }
  58. if ($rid) {
  59. $uids = db_select('users_roles', 'ur')
  60. ->fields('ur', array('uid'))
  61. ->condition('ur.rid', $rid)
  62. ->execute()->fetchCol();
  63. if (!empty($uids)) {
  64. $query = new EntityFieldQuery();
  65. $query->entityCondition('entity_type', 'user')
  66. ->propertyCondition('uid', $uids, 'IN');
  67. if ($active_user) {
  68. $query->propertyCondition('status', 1);
  69. }
  70. $entities = $query->execute();
  71. if (!empty($entities)) {
  72. $users = user_load_multiple(array_keys($entities['user']));
  73. }
  74. }
  75. }
  76.  
  77. return $users;
  78. }