RSS

Newsletter

The CodeKarate Newsletter is the best way for technical ninjas to keep their swords sharpened. Don't worry, we won't flood your inbox and your email address will always remain private.
Back to Top

Drupal 7 getting all members of an Organic Group

Simple function that gets a list of all users subscribed to an organic group.

/**
 * Get all users of a group
 */
function _get_users_in_group($gid) {
  $query = db_select('users', 'u');
 
  $query
    ->condition('u.uid', 0, '<>')
    ->condition('u.status', 1, '=')
    ->fields('u', array('uid', 'name'))
    ->join('og_membership', 'ogm', "ogm.gid = :gid AND u.uid = ogm.etid AND ogm.entity_type = 'user'", array(':gid' => $gid));
  return $query->execute();
}

You can then loop through the results using something like:

// Get a list of all the users in the group
$group_members = _get_users_in_group($node->nid);
 
// Loop through and load each user
foreach ($group_members AS $member) {
  // Load the user object if necessary
  $user = user_load($member->uid);
 
  // Do whatever else you need to
}

If you know of an alternative way to do this, let me know in the comments.

Discussions

1
Frederic (not verified)

nice share

thanks for sharing, just wat i need!

2
Rob (not verified)

Huge help :-p

Thanks for sharing… Just helped me with a patch (http://drupal.org/node/871238#comment-6729476). I skipped the JOIN though… I thought I didn't need any fields from the user table, but I'm nto checking the user status. Hmm, grump. That's probably important, isn't it?

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <blockquote> <img>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <php>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <python>, <ruby>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.