Dynamic Sharing of Standard & Custom Objects through Salesforce Apex

Apex Sharing is sharing record access through a program using Salesforce Apex through which can grant access to users or groups of users.

We can use the Salesforceuser interface and Force.com for Apex Sharing.

Apex sharing for partner account supports scenarios such as Account sharing, Case Sharing, Opportunity sharing, Lead sharing, and Custom Object Record sharing. Sharing sets are not available for partner communities, only customer communities. This code allows for standard and custom objects to be shared with a partner account.

Apex sharing for standard object:

Let’s take an example: Account

In standard objects, the field ParentId and AccessLevel have object name prefixed. As an example in AccountShare object, these fields are called AccountId and AccountAccessLevel respectively.

The following code finds all accounts owned by a user and shares them with their respective portal user.

Below you can see the code to create sharing rule for Account object through Apex. Each object has its own sharing object. In this case, it is “AccountShare”

For (User u : [SELECT Id FROM User where User.Profile.UserLicense.Name = 'Partner Community']) 
{
    AccountShare a = new AccountShare();
    a.AccountId = acc.id;  // record to which  we need to give access to.
    a.UserOrGroupId = u.Id; //Set the portal user Id to share the accounts with
    a.AccountAccessLevel = accesslevel;
    a.OpportunityAccessLevel = accesslevel;
    a.RowCause = 'Manual';
    shrobjlst.add(a);
}
Insert shrobjlst;

Apex sharing for custom object:

Let’s take an example: Employee Custom Object

The fields of share object for custom objects that should be filled in are explained below:

Field name in
Custom Object

Description

ParentId

The Id of the object to which access is being granted

UserOrGroupId

The id of user or group to which access is being granted

AccessLevel

“Read” or “Edit” or “All”

As an example, for custom object Employee__c, share object will be called  Employee __share (note that c after the custom object name is removed).

In the first example, we create a share for a custom object.

shrobjname  = Employee__share;

For (User u : [SELECT Id FROM User where User.Profile.UserLicense.Name = 'Partner Community']) 
{
    sObject empShare = Schema.getGlobalDescribe().get(shrobjname.toLowerCase()).newSObject(); 
    empShare.put('ParentId',empID.Id) ;
    empShare.put('UserOrGroupId',u1.Id) ; //Set the portal user Id to share the accounts with
    empShare.put('AccessLevel',accesslevel) ;  
    empShare.put('RowCause','Manual');  
    shrobjlst.add(empShare);  
}
Insert shrobjlst;