[Drupal] How can we assign different groups for a user and retrieve using Organic Group in Drupal 7?

| | 2 min read

In one of my Drupal project, we had a requirement to set a 2 level arrangement for users group. That means, we want to add more than one group for a user, in one of our Drupal site. Our experts find a solution for this by implementing Organic Group with user's account by some custom codes. Do you have a requirement like this? Connect with us.

Organic Group(OG) is a powerful and useful module in Drupal. We can create groups using OG and also assign users to them. OG module saves the custom additions to the users object into the database. OG membership entity that links users and content/entity to their associated group also. If you want to assign a user to different groups, then you can use the following codes.

//Sample group definition.
  $groups = array("Group A", "Group B", "Group C",...);
  global $user;
  $uid = $user->uid;
  $account = user_load($uid);
  foreach($groups as $group_id) {
    og_group('node', $group_id, array(
      "entity type"  => "user",
      "entity"  => $account,
      "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
    ));
  }

The 'og_get_groups_by_user' function can be used for getting user's group. We get all the groups that a user belongs to by passing the user membership object. This can be executed by using the following codes.

  function module_name_get_user_groups() {
    global $user;
    $uid = $user->uid;
    $account = user_load($uid);
    $group_ids = og_get_groups_by_user($account);
  }

Note that, select Organic Groups field settings in OG administration page for adding the special Organic Groups fields. Have fun, lets read OG related articles from here. Do you have any more queries like this? Just type over here.