[SalesForce] SOQL to find whether user’s role is part of the public group

I have few public groups where I have only roles added. Is there any way to identify whether the current user is part of the group by taking current user's role and then comparing with the roles added in the group?

I would like to build a SOQL to check whether my current user is part of the group, but with below SOQL it is returning always false –

SELECT GroupId,UserOrGroupId FROM GroupMember WHERE GroupId =: <-----> AND UserOrGroupId =: <---->

Best Answer

Since Role is mapped in user record so retrieve UserRoleId from User

In the Group object , RelatedId field stores following types of values:

  • Role
  • RoleAndSubordinates

Though Group can have other Type as follows which doesn't have RelatedId

  • Organization
  • Queue
  • Regular

So, final query will be like this

SELECT Id,Name,DeveloperName,RelatedId,Type FROM Group 
WHERE RelatedId IN 
     (SELECT UserRoleId FROM User WHERE Id = <UserId>) 
AND Type = 'Role'

Also, refer Fetch public groups for a user via Apex for all types of complex scenarios.

Here is an example from my DE

user group

SOQL and results

SOQL

Related Topic