Salesforce Apex-based record sharing

In Salesforce, Apex-based record sharing allows you to programmatically share records with users or groups based on specific criteria or conditions. This is useful when you need to dynamically adjust record access beyond what can be achieved through standard sharing settings or manual sharing.

Create Apex Sharing Reasons

Share Objects and Fields

StandardObjectNameShare

Example

Let's say you want to share records with relators who belong to the "Sales" role. Here's an Apex class that uses Apex sharing to share records with users who meet the defined criteria.

public class RecordSharingController {
    
    public static void shareRecords() {
        // Query records that meet the sharing criteria
        List<House__c> recordsToShare = [SELECT Id FROM House__ c WHERE Status__c = 'In Market'];
        
        // Create a list to hold new sharing objects
        List< House__Share > shareRecords = new List< House__Share>();
        
        // Iterate over the records to share
        for(House__c record : recordsToShare) {
            // Create a new sharing object
            House__Share shareRecord = new House__Share();
            
            // Set the record ID and access level
            shareRecord.ParentId = record.Id;
            shareRecord.UserOrGroupId = [SELECT Id FROM User WHERE UserRole.Name = 'Sales' LIMIT 1].Id; // Assuming the role exists
            shareRecord.AccessLevel = 'Read'; // Set the desired access level
            
            // Add the sharing object to the list
            shareRecords.add(shareRecord);
        }
        
        // Insert the sharing records
        if(!shareRecords.isEmpty()) {
            insert shareRecords;
        }
    }

}




Record Sharing Reason

Custom share reasons cannot be mentioned, Salesforce will assign Manual as a share reason if the line is skipped.

AccountShare.RowCause = Schema.AccountShare.RowCause.Manual;

If sharing reason is not mentioned, the default is Manual.

House__Share.RowCause = Schema. House__Share.RowCause.House_Still_In_Market__c;

Custom sharing reason is available for custom objects only in Salesforce Classic.

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach