Monday, August 5, 2019

Generic Methods to Share sObject Record using Apex in Salesforce


Apex Class

public inherited sharing class SharingUtility {
    
    // For Standard Object Record
    public static list<SObject> createSharingForStandardObject(String strShareObjectName, String strParentField, map<Id, set<Id>> mapObjectIdUserIds, String strAccessLevelFieldName, String strAccessLevel, String strRowCause) {
        SObjectType objectType = Schema.getGlobalDescribe().get(strShareObjectName);
        list<SObject> lstObjects = new list<SObject>();
        
        for(Id objectId : mapObjectIdUserIds.keySet()) {
          for(Id userOrGroupId : mapObjectIdUserIds.get(objectId)) {
            SObject shareRecord = objectType.newsObject();
            shareRecord.put(strParentField, objectId);
            shareRecord.put('UserOrGroupId', userOrGroupId);
            shareRecord.put(strAccessLevelFieldName, strAccessLevel);
            shareRecord.put('RowCause', strRowCause);
            lstObjects.add(shareRecord);
          }
        }
        
        if(!lstObjects.isEmpty()) {
         insert lstObjects;
        }
       return lstObjects;
    }
    
    // For Custom Object Record
    public static void createSharingForCustomObject(String strShareObjectName, map<Id, set<Id>> mapObjectIdUserIds, String strAccessLevel, String strRowCause) {
        SObjectType objectType = Schema.getGlobalDescribe().get(strShareObjectName);
        list<SObject> lstObjects = new list<SObject>();
        
        for(Id objectId : mapObjectIdUserIds.keySet()) {
          for(Id userOrGroupId : mapObjectIdUserIds.get(objectId)) {
            SObject shareRecord = objectType.newsObject();
            shareRecord.put('ParentId', objectId);
            shareRecord.put('UserOrGroupId', userOrGroupId);
            shareRecord.put('AccessLevel', strAccessLevel);
            shareRecord.put('RowCause', strRowCause);
            lstObjects.add(shareRecord);
          }
        }
        
        if(!lstObjects.isEmpty()) {
         insert lstObjects;
        }
    }

}
Ex:
SharingUtility.createSharingForStandardObject('CaseShare', 'CaseId', new map<Id, set<Id>>{currentCase.Id => new set<Id>{currentCase.CreatedById}}, 'CaseAccessLevel', 'Edit', 'Manual');

No comments:

Post a Comment