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"