Apex based sharing a record with a User or Public Group is easy and direct. Below is the sample sharing of an Account record with a user.

AccountShare Acctshr = new AccountShare();
Acctshr.AccountId = aid;
Acctshr.UserOrGroupId = 'User.Id';
Acctshr.AccountAccessLevel = 'Edit';
Acctshr.OpportunityAccessLevel = 'Edit';
Database.SaveResult sr = Database.insert(Acctshr,false);

But how do you share with a Role (like criteria based sharing rules) using Apex code. You cannot directly replace User.Id with Role.Id in the above code.

Instead need to get the Role.Id using the below query.

Group grp = [Select Id,Name,RelatedId,Type From Group where RelatedId IN (select Id from userRole where DeveloperName='xxxxx')];

SOQL Query to get Role

What’s to note here is the Type of the Group. It is either ‘Role’, ‘RoleAndSubordinates’ and ‘RoleAndSubordinatesInternal’

AccountShare Acctshr = new AccountShare();
Group grp = [Select Id,Name,RelatedId,Type From Group where RelatedId IN (select Id from userRole where DeveloperName='xxxxxx') and type='RoleAndSubordinates'];
Acctshr.AccountId = aid;
Acctshr.UserOrGroupId = grp.Id;
Acctshr.AccountAccessLevel = 'Edit';
Acctshr.OpportunityAccessLevel = 'Edit';
Database.SaveResult sr = Database.insert(Acctshr,false);

Choose the type based on what type of sharing you need. Happy Sharing!

Advertisements