[SalesForce] Dynamically assigning sharing reason to Object

I am trying to assign dynamically rowcause reason to my custom objects but erroring out like below:

//Smaple Map Format

recordIdsMap.put(objetapiname, Record);





for (String obj: recordIdsMap.keySet()) { //This will fetch names of objects defined in custom setting
    //if(i<10){
            if (obj.contains('__c')) {

                String objName = obj.split('__')[0];
                system.debug('---' + obj);
                access = 'AccessLevel';
                pId = 'ParentId';
                ShareObject = objName + '__Share';
                ShareObject2 = objName + '__Share';
                system.debug('PJJJJ' + ShareObject);
           }else {
                ShareObject = obj + 'Share';
                access = obj + 'AccessLevel';
                pId = obj + 'Id';
                system.debug('PJJJJ2' + ShareObject);
    }






Schema.SObjectType sobjType = gd.get(ShareObject2);

     //Here are i am trying to get my Rowcausereason in string 


//string RowcauseReason = Schema.sobjType.rowCause.ApexSharing__c;

        string RowcauseReason = Schema.ShareObject.rowCause.ApexSharing__c;

But its showing compile time error as below :

Variable does not exist: Schema.sobjType.rowCause.ApexSharing__c at
line 264 column 37

Please suggest, thanks.

Best Answer

Apex managed sharing doesn't work quite the way you seem to be attempting to use it. The only sharing reason that will exist by default is "manual". Any other reasons need to be defined on the Object's detail page. From the Apex Docs:

Apex sharing reasons are defined on an object's detail page. Each Apex sharing reason has a label and a name:

The label displays in the Reason column when viewing the sharing for a record in the user interface. This label allows users and administrators to understand the source of the sharing. The label is also enabled for translation through the Translation Workbench.

The name is used when referencing the reason in the API and Apex. All Apex sharing reason names have the following format:

MyReasonName__c

Apex sharing reasons can be referenced programmatically as follows:

Schema.CustomObject__Share.rowCause.SharingReason__c

For example, an Apex sharing reason called Recruiter for an object called Job can be referenced as follows:

Schema.Job__Share.rowCause.Recruiter__c

See Creating User Managed Sharing Using Apex for more on the topic.

Related Topic