[SalesForce] Creating Sharing Rules on run-time(While opportunity is being saved/edit) using apex code

Is it possible to create sharing rules at run-time? If yes then please explain how can we do that in save method/trigger?

Actually i need to bypass role hierarchy setting and for that i need to create Sharing Rules at run-time to give a particular user(is a field on opportunity) to edit right on that opportunity. Actually that particular user comes below in role hierarchy than the owner of opportunity.

Best Answer

AFAIK you cannot create a sharing rule at runtime. But yes you can share the opportunity to the user (which as per you question is a field in the oppty). You can insert a record in the opportunityShare object which will give either read or write access. You can add the below code in the an after insert trigger / after update trigger of opportunity.

opportunityShare opptyShare = new opportunityShare();
opptyShare.OpportunityAccessLevel = 'Read';// other values that can be added are 'Edit' and 'All'
opptyShare.OpportunityId = opptyID; //add the oppty Id which you want to share.
opptyShare.UserOrGroupId = userId; //add the UserId which to which you want to share the oppty
insert opptyShare; // insert the oppty share records.

You can read more about it here : http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_opportunityshare.htm

Related Topic