I would like to get a list of all the users who have been assigned a certain role. I could write my own SQL but I would like to use the api as much as possible.
You can use entity_load to get array of users. Here is the sample that will create list of all emails for admin users (used to send notification)
<?php
$users = entity_load('user');
$emails = '';
foreach($users as $user) {
if (array_key_exists(3, $user->roles)) {
if (strlen($emails) > 0) {
$emails .= ' ' . $user->mail;
} else {
$emails = $user->mail;
}
}
}
?>
There are generally no Drupal API functions for this sort of task (pulling up entities that match certain criteria). It tends to focus on single-entity CRUD functions in the API; everything else is up to a developer's own SQL skills.
The Views module allows you to build lists of users filtered by role, permission, etc -- but it could easily be overkill.
The SQL that worked for me:
$users = ""; $result = db_query('SELECT users.name AS users_name FROM users users INNER JOIN users_roles users_roles ON users.uid = users_roles.uid WHERE users_roles.rid = 4'); while ($existing_user = db_fetch_object($result)) { if ($users != "") $users .= ", "; $users .= $existing_user->users_name; // or do whatever } echo $users;
Keep in mind this is for Drupal 6 and I'm not sure about the performance of this for large user bases. Not sure about Drupal 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With