Query Indirect GroupMember Records

public-grouprolessoql

Is there a way to query GroupMembers who have been granted access indirectly, i.e. via a UserRole?

enter image description here

The GroupMember docs imply that no records are created but they are shown in the UI, so I am hoping it possible. For my scenario I really only need to be aware of the Role Id/Group Member. I do not need to traverse up through the role hierarchy.

A record exists for every User or Group who is a direct member of a
public group whose Type field is set to Regular. User records that are
indirect members of Regular public groups are not listed as group
members. A User can be an indirect member of a group if he or she is
in a UserRole above the direct group member in the hierarchy, or if he
or she is a member of a group that is included as a subgroup in that
group.

enter image description here

Best Answer

My experimentation seems to indicate that for a UserRole you add to a Group, Salesforce adds a Group with Type = 'Role' and RelatedId = <UserRole.Id>. You may need to separately process RoleAndSubordinates and/or RoleAndSubordinatesInternal, depending on your requirements.

Regardless, you should be able to query for the Id of the UserRole by iterating through the GroupMember records and filtering by Type. As there are many Type values to inspect, if you want to properly handle all of them you may need to do more legwork, as you shouldn't trust my back-of-the-napkin implementation. But it should get you started, hopefully.

Set<Id> roles = new Set<Id>();
Set<Id> rolesWithSubordinate = new Set<Id>();

Set<Id> groupIds = new Set<Id>();
for (GroupMember member : myGroup)
    groupIds.add(member.UserOrGroupId);

for (Group record : [
    SELECT Type, RelatedId FROM Group WHERE Id IN :groupIds
]){
    switch on record.Type
    {
        when 'Role'
        {
            roles.add(record.RelatedId);
        }
        when 'RoleAndSubordinates'
        {
            rolesWithSubordinate.add(record.RelatedId);
        }
    }
}
// query users with the above roles here
Related Topic