+ Start a Discussion
Prateek Jain 46Prateek Jain 46 

Dynamically assigning sharing reason to Object

Hi All,

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 (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    
Vasani ParthVasani Parth
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.  Here's the link : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_bulk_sharing_creating_with_apex.htm?search_text=Creating%20User%20Managed%20Sharing%20Using%20Apex

Please mark this as the best answer if this helps
Prateek Jain 46Prateek Jain 46
HI Vasani, thanks for your quick response, i have created apex sharing reasons on objects as "ApexSharing" but actually not able to get shareobject instance dynamically here :


here in "ShareObject"  if i use hardcode api name of shareobject it will work , but i cannot hard it so need to pass object of it , any idea on this, thanks.
BM 5BM 5
Can you please try the below code.

Schema.SObjectType testShareType = Schema.getGlobalDescribe().get('Test__Share');
SObject testShare = testShareType.newSObject();
testShare.put('ParentId', 'a00G00000099pyM');
 testShare.put('UserOrGroupId', UserInfo.getUserId());
 testShare.put('AccessLevel', 'Read');
testShare.put('RowCause', 'Test__c');
insert testShare;
Ashok RathvaAshok Rathva
Thanks, @BM 5 above solution worked for me to assign dynamic values to RowCause.