TODO: overview of entity types, field types, and how they all glue together.

Working with groups and group content

Given an entity that is group content:

    $wrapper = entity_metadata_wrapper(ENTITY_TYPE, $entity);
    $og_membership_entity = $wrapper->og_group_ref->value();

Comments

DamienMcKenna’s picture

Something that would be useful to know:

  • How to obtain a list of members for a given group entity.

--
Damien McKenna | Mediacurrent

quadcomm’s picture

@DamienMcKenna

  • How to obtain a list of members for a given group entity.

Have you figured out how to do this? After 1 hour of research it looks like we have to write a custom SQL statement just to grab a list of group members. I have a hard time believing this as I thought there would be an existing function like og_get_members($gid);

quadcomm’s picture

Here's the Drupal 7 solution to programmatically obtain the names of group members after specifying a Group ID:

      $sql = "SELECT name FROM users u
               INNER JOIN og_membership ogm ON u.uid = ogm.etid
               WHERE ogm.gid = '$MY_GROUP_ID'
               AND ogm.entity_type = 'user'";

      $user_list = db_query($sql)->fetchAll();

This is much faster (at least 3x faster) than using a Drupal function including EntityFieldQuery();

DamienMcKenna’s picture

A small helper function to load all of the group nodes that the user is a member of:

/**
 * Provide an array of groups the member is in.
 *
 * @param $uid integer
 *   The user's uid.
 *
 * @return array
 *   An array of the full group objects, presumably nodes.
 */
function example_load_user_groups($uid) {
  // Load the user.
  $account = user_load($uid);

  // Build a list of the groups.
  $groups = array();
  if (!empty($account->og_user_node[LANGUAGE_NONE][0]['target_id'])) {
    // Load each group object. Note: this assumes the objects are nodes.
    // TODO: Clear the entitycache object when the nodes are modified.
    foreach ($account->og_user_node[LANGUAGE_NONE] as $gref) {
      if (!empty($gref['target_id']) && is_numeric($gref['target_id'])) {
        $groups[$gref['target_id']] = node_load($gref['target_id']);
      }
    }
  }

  return $groups;
}

--
Damien McKenna | Mediacurrent