How to Create an Apex Sharing Reason in Salesforce (Custom Objects)

On custom objects, you can define Apex Sharing Reasons—named reasons that label why programmatic access was granted. In Setup, open your custom object, find Apex Sharing Reasons, and click New. Salesforce exposes that reason in Apex as an enum under Schema.Object__Share.RowCause, so your code can insert Object__Share rows with a precise RowCause (for example, Schema.Invoice__Share.RowCause.Sales_Oversight__c). This improves traceability and makes later maintenance straightforward. 

For durability, pair the reason with Apex Managed Sharing Recalculation. Create a Batch Apex class that recomputes intended grantees and associate it with the custom object (Setup → the object → Apex Sharing Recalculation). Salesforce runs this class when OWD changes and allows you to run it programmatically as well. During recalculation, the platform removes shares that no longer add access—so keeping logic idempotent is key. 

Note: Only users with Modify All Data (or appropriate elevated permissions) can add or change Apex-managed shares on a record. Plan to run your maintenance batches under a privileged integration user. 

SFDC247

Leave a Reply

Your email address will not be published. Required fields are marked *