4

I had been wondering if there is a simple solution to find out the different groups that a user is a part of, either by direct membership or via a sub groups or even deep.

We were facing a challenge where we wanted to find out if a user belongs to a certain group and based on that, certain actions were made possible.

Querying the group member object was a solution but to a certain extent.

Lets take an example. User A is a part of Group A. Group A is a part of Group B. Group B is a part of Group C. So, User A is indirectly a part of Group B and Group C.

So the apex query would return us Group A but not Group B and Group C.

What is the solution to this? I have one which I am going to post as an answer (possible). Please provide your suggestions / improvements.

1
1

If you navigate to the user detail page, there is a section for Group Memberships. If there are more than 5 records under the list, you will get a link 'Go To List' that takes you to the list of groups. We have made use of this page.

Here is the code snippet.

//create a page reference to the standard salesforce page.
//pass the id of the user in context.
PageReference page = new PageReference('/_ui/system/user/GroupMembershipPage/d?userId=005Q000000O4AK6');

//get the html content of the page
String html = page.getContent().toString();

//set of group ids
Set<Id> groupsIds = new Set<Id>();

//if you study the html code of the page, you will understand the below string we have used for the string functions.
while(html.contains('/setup/own/groupdetail.jsp?id=')) {
    html = html.subString(html.indexOf('/setup/own/groupdetail.jsp?id=') + 1);
    String groupId = html.subString(html.indexOf('=') + 1 , html.indexOf('"'));
    System.debug('***** ' + groupId);
    groupIds.add(groupId);
}
0

You can write recursive function that drill down one level each time.

This many not work for very large link list of groups but for up to 10 groups it should work fine.

1
  • Yes that is the main problem. – Chetan Gupta Jun 24 '14 at 15:35

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.