I am currently trying to do a proof of concept in my org. We are running into a situation where we will eventually have maxed out our manual sharing rules and are looking at a way to create sharing rules via apex for several different objects. Our current proposed solution looks like this. Custom Object in question

The proposed solution is for a user to simply input a client and user for which to share the client record in the custom object above, then write a trigger on the object that will create the apex sharing rule. So my questions are

  1. Is this even possible?
  2. Is this scalable? Say that you wish to share the contacts associate with the client in this trigger?

I have a bit of code started but frankly I am a novice and not familiar with the rules in Salesforce

trigger SharingRuleCreationTrigger on Sharing_Configuration__c (after insert) {
    // Create a new list of sharing objects for Job
        List<Client__Share> clshr= new List<Client_Share>();
        Client_Share user;
        Map<ID,Client__c> cm =new Map<ID,Client__c>;
        Set<Id> CID = new Set<Id>();
        for(Sharing_Configuration__c SC: Trigger.new){
                if(SC.Client__c  != null){
        for (Client__c C : [
                        SELECT Id
                        FROM Client__c
                        WHERE Id IN :CID])
                if (!cm.containsKey(c.Id)) {
                    cm.put(c.id, c);

Any help would be appreciated!

  • I think you have a terminology issue? You appear to want to create Share records, not Sharing Rules. The latter would be impossible in Apex, and not scalable. The former, however, is actually trivial in nature.
    – sfdcfox
    Commented May 19, 2021 at 4:21

1 Answer 1


For standard objects, you can use the Share tables (e.g. AccountShare for sharing an Account, ContactShare for a Contact, etc), and for custom objects, you can either use the tables (e.g. Custom_Object__Share), or you can interface with Apex Managed Sharing (AMS). Given you plan on storing the settings in an object, AMS provides a good opportunity to leverage your custom data to even "recalculate" the "rules" (which you've defined programmatically) to ensure that all existing records are covered. This gets a bit technical, so you'll want to read the documentation two or three times to make sure you get the concepts, but it's actually pretty easy once you get the hang of it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .