You need to sign in to do that
Don't have an account?

Determine the Public Groups a User Is In
I am working on something where I want to allow an admin to assign items to a Public Group. Then, at runtime, I need to determine what Public Groups a user is in (directly or via Roles / Roles + Subordinates) and display the appropriate items. Because Public Groups can be complicated having other Public Groups as Members and also Roles & Subordinates, figuring out the Groups a user is in can be difficult.
I started a conversation on Twitter about it and then did some research and have a starting point. I'd like to encourage others to help me vet this and then it could become a Cookbook item down the line. Here's what I got...
I think this can be done in 2 steps without much looping. From what I can tell, the Group table can contain all kinds of Groups ("Regular" Public Groups, Roles, Soles & Subordinates, Queues, etc.). The Group Member table seems to only contain pointers to Users or to Other Groups. Groups that are copies of Roles and Roles & Subordinates have a Related Id filled in.
I believe the following 2 queries could determine the Public Groups that a User is actually in...
1) Query the Group table to get the Group records where the Related Id = the users's role. We could filter for Type of Role or RoleAndSubordinates, but it seems that anything with a RelatedId filled in is one of those types. This query is essentially getting the Group records that mirror our Role record.
List<String> roleRelatedGroupIds = new List<String>(); for (Group g : [SELECT id, RelatedId, Type FROM Group where RelatedId= :UserInfo.getUserRoleId()]{ roleRelatedGroupIds.add(g.id); }
2) Next we query the Group Member table for records where our user is specifically assigned and also include records where our role is assigned.
List<String> allGroupIDs = new List<String>(); for (GroupMember gm : [SELECT Id, group.id, group.name, group.type FROM GroupMember where (UserOrGroupId = :UserInfo.getUserId() AND group.type='Regular') OR (UserOrGroupId IN :roleRelatedGroupIds AND group.type='Regular')]{ allGroupIDs.add(gm.group.id); }
I'd need to hack at this given lots of users and lots of Group Types like Queues, Territories, Roles, Public Groups, etc. From what I've been able to test, this works.
Grrr. This works unless you start layering Groups in Groups in Groups
An idea for a method in Apex was logged at https://sites.secure.force.com/success/ideaView?c=09a30000000D9xtAAC&id=08730000000XoM2AAK
Go vote!
i use this for groups in groups in groups.
and then this to traverse the hierarchy for roles.
@Walter TY for this code , I have much use for it.