Switch global roles for members in an organic group

Public

This function accepts a group object as input and then performs an operation on all users in that group of a certain role. The use case for this would be triggering an event that requires all users to lose a role and gain a new one (like a state change but for user role). The next snippet loads everyone of a certain role in a given group, this one performs the role swap.

Get raw version
php
  1. define('OLD_ROLE', 'student');
  2. define('NEW_ROLE', 'past student');
  3.  
  4. /**
  5.  * Handle Role transformation.
  6.  */
  7. function _switch_roles_of_group_users($group) {
  8. // Get a list of all the users in the group
  9. $users = _users_in_group($group->nid);
  10. // add new role
  11. $role = user_role_load_by_name(NEW_ROLE);
  12. user_multiple_role_edit($users, 'add_role', $role->rid);
  13. // drop old role
  14. $role = user_role_load_by_name(OLD_ROLE);
  15. user_multiple_role_edit($users, 'remove_role', $role->rid);
  16. }

This function returns all users in a group that match a certain role, in this case the OLD_ROLE (by name) that's given in the previous snippet. This joins user role and group membership tables and filters out only those items that are of a certain role. The returned information is used above

Get raw version
php
  1. /**
  2.  * Get all users of a group by role
  3.  */
  4. function _users_in_group($gid) {
  5. // load full student role object by name
  6. $role = user_role_load_by_name(OLD_ROLE);
  7. // return membership to this group that are students
  8. $query = db_select('og_membership', 'ogm');
  9. // join user roles and memberships
  10. $query->join('users_roles', 'ur', 'ur.uid = ogm.etid');
  11. // only this group
  12. $query->condition('ogm.gid', $gid, '=');
  13. // ensure it's a user type of entity
  14. $query->condition('ogm.entity_type', 'user', '=');
  15. // only grab people who are students
  16. $query->condition('ur.rid', $role->rid, '=');
  17. // return the entity id which is the user's id
  18. $query->fields('ogm', array('etid'));
  19. // execute
  20. $result = $query->execute();
  21. $records = $result->fetchAll();
  22. $uids = array();
  23. // convert to an array of uids
  24. foreach ($records as $record) {
  25. $uids[] = $record->etid;
  26. }
  27. return $uids;
  28. }