Find your content:

Search form

You are here

Can we use Dynamic Apex to Share a Record?

 
Share

One of the most common use cases not supported by sharing rules is when we have a lookup field to the user object and whomever is selected in the lookup field will automatically get read/write access to the record.

Can we design a reusable code/trigger to do this? Its one of the most common things that we had to create a trigger for.

More information on creating a trigger: http://wiki.developerforce.com/page/Using_Apex_Managed_Sharing_to_Create_Custom_Record_Sharing_Logic

I've had some success using the following code:

LeadShare leadShare = new LeadShare();
leadShare.ParentId = '00QC00000121LCI';
leadShare.UserOrGroupId = '005C0000003N5lT';
leadShare.AccessLevel = 'edit';
insert leadShare;

Here are some of my considerations: - How can we get the different rowCause from Apex? - How can we determine if the OBJECTNAME__Share is available?

Feel free to share other information that need to be considered. Thanks!


Attribution to: Joey Chan

Possible Suggestion/Solution #1

Just tried this with an object called Test, with a Reason also called Test. Hope this helps!

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;

If the object does not have a sharing object 'testShareType' in the example above will be null.


Attribution to: Andrew Fawcett
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3613

My Block Status

My Block Content