A2oz

How Do I Enable Apex Managed Sharing in Salesforce?

Published in Salesforce Development 2 mins read

Apex managed sharing allows you to define sharing rules using Apex code. This gives you more control over data access and security than standard Salesforce sharing rules.

To enable Apex managed sharing, follow these steps:

  1. Enable Apex Managed Sharing for your organization:

    • Navigate to Setup in your Salesforce org.
    • In the Quick Find box, enter Sharing Settings.
    • Select Sharing Settings.
    • Under Apex Managed Sharing, check the box next to Enable Apex Managed Sharing.
    • Click Save.
  2. Create an Apex class:

    • Write Apex code to define your sharing rules.
    • Use the SharingRecalculation class to manage sharing calculations.
    • Implement the calculateSharing method to determine the users and groups who should have access to specific records.
  3. Update the record sharing model:

    • Select the record type for which you want to enable Apex managed sharing.
    • In the Sharing section, choose Apex Managed Sharing.
    • Save your changes.

Example Apex Code:

public class AccountSharingCalculation extends SharingRecalculation {

    public override void calculateSharing(List<SObject> records, Map<Id, SObject> oldMap) {
        // Iterate through the list of Account records.
        for (Account acc : (List<Account>)records) {
            // Check if the Account is owned by a specific user.
            if (acc.OwnerId == '005D0000001p112AAA'){
                // Grant access to the Account to a specific group.
                acc.SharingRecalculation.add('00G00000001p113AAA', 'Read');
            }
        }
    }
}

Practical Insights:

  • Apex managed sharing is beneficial when you need complex or dynamic sharing rules that cannot be achieved with standard sharing rules.
  • You can use Apex managed sharing to implement custom sharing logic based on specific business requirements.
  • It's essential to carefully test your Apex code to ensure it works correctly and doesn't create security vulnerabilities.

Solutions:

  • Use the SharingRecalculation class: This class provides the necessary methods and tools for managing sharing calculations.
  • Implement the calculateSharing method: This method is responsible for determining the users and groups who should have access to specific records.
  • Use SharingRecalculation.add method: This method adds a user or group to the sharing list with specific access levels (Read, Edit, Delete, Full).

Related Articles