0

I am using drupal 7, I want to add users having role 'R' to a OG group 'G'.

Is it possible to do that?

1 Answer 1

1

Here's some code I've used, you can't add the role condition to EntityFieldQuery so the array needs to be filtered afterwards:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
      ->propertyCondition('uid', '1', '>'); // skip the anonymous and admin
  $entities = $query->execute();
  $uids = array_keys($entities['user']);
  $accounts = user_load_multiple($uids);

  // filter the users array by role
  $include_roles = array('my_role', 'my_other_role');
  $filter = function ($value) use ($include_roles) {
        $isect = array_intersect($include_roles, $value->roles);
        return !empty($isect);
      };
  $accounts = array_filter($accounts, $filter);

Then, to add these to your group having id $gid

  foreach ($accounts as $account) {
    og_group($gid, array('entity' => $account, 'state' => OG_STATE_ACTIVE));
  }

Hope this helps. I think this should be doable in Rules, but I'm no expert in that.

6
  • 1
    Yes, seems you can make a Rule that gets run on "After updating an existing user account"/"After saving a new user account", set a "User has role(s)" condition and "Subscribe user to group" in the action. Don't know how to do that on all existing users in Rules though.
    – vjik--
    Jul 5, 2012 at 16:34
  • Thanks for the answer, but in which file do i add the snippet?
    – Shashank
    Jul 6, 2012 at 11:14
  • The quickest way is to use the Devel module to execute PHP on your site (do be careful with that and try it on a testing site first), or write a custom module (tutorial: drupal.org/node/1074360 ) and make a menu callback for the function that executes the code. For continously subscribing users that get role X into group Y it's best to use the Rules module as described - you wouldn't want to load and go through every single user more than once.
    – vjik--
    Jul 6, 2012 at 12:23
  • i am no good in using codes, but i will surely try to apply these codes.
    – Shashank
    Jul 6, 2012 at 12:36
  • Is this solved in any way? Can this be done with rules? Event: After saving a new user account, Condition: User has role(s)... but the action is a problem if you want to give that user an arbitrary group membership? (not from context but manually set the NID of the group).
    – Rosamunda
    Mar 16, 2013 at 4:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.