How can I programmatically get a list of member entities of an Organic Group?
(I know how to get a list of group members using Views — I'd prefer to do this using the Organic Groups API, but haven't been able to find the right method.)
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityHow can I programmatically get a list of member entities of an Organic Group?
(I know how to get a list of group members using Views — I'd prefer to do this using the Organic Groups API, but haven't been able to find the right method.)
Using directly the Organic Groups API:
og_get_group_members_properties($yourGroupNode, array(), 'members', 'node');
gives you an array of user ids.
To obtain only active, pending or blocked users, you can put 'members__1', 'members__2' or 'members__3' in place of 'members', like in this example:
og_get_group_members_properties($yourGroupNode, array(), 'members__1', 'node');
of, if you prefer, like this one:
og_get_group_members_properties($yourGroupNode, array(), 'members__' . OG_STATE_ACTIVE, 'node');
Example of the returned value:
Array
(
[0] => 48
[1] => 49
[2] => 51
)
Or via DBTNG:
$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $yourGroupID, "=");
$query->condition("ogm.group_type", "node", "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();
print_r($result->fetchAll());
...which allows you to join other tables, rather than having to filter the result set in PHP code as you would if using EntityFieldQuery
.
$query = new EntityFieldQuery();
$query
->entityCondition("entity_type", "og_membership", "=")
->propertyCondition("gid", $yourGroupID, "=");
$result = $query->execute();
print_r($result["og_membership"]);
(Based on http://api.drupal.org/api/drupal/includes--common.inc/function/entity_load/7#comment-14544)
smokris solution worked but I found another way with EntityFieldQuery
:
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->fieldCondition('og_group_ref', 'target_id', $yourGroupID)
->execute();
Example of the returned value:
{"node":
{"22":{"nid":"22","vid":"22","type":"panoramique"},
"32":{"nid":"32","vid":"32","type":"panoramique"},
"35":{"nid":"35","vid":"35","type":"panoramique"},
"36":{"nid":"36","vid":"36","type":"panoramique"}
}
}
Extending answer from @smokris.
The active status for the memberships is "1" (->condition('ogm.state', 1, '=')
).
function _get_users_in_group($gid) {
$query = db_select('users', 'u');
$query
->condition('u.uid', 0, '<>')
->condition('u.status', 1, '=')
->condition('ogm.state', 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();
}