[SalesForce] Using Apex Managed Sharing to share an opportunity

Here's the use case. When a lead is converted to an Opportunity, I want to automatically share the opportunity with the previous owner of the lead. This is needed because upon conversion, the opportunity ownership is granted to someone else but the original lead owner needs ongoing access to the opportunity.

So:

  • A partner submits/creates a lead and is the lead owner
  • Lead is converted to opportunity and internal sales person gains ownership
  • Original partner needs to have view/edit access on this opportunity

I know you can use Apex Managed Sharing to share a custom object, but I'm hitting a wall trying to do this with an opportunity since the fields in OpportunityShare are not writable. The following won't even compile as a result:

List<OpportunityShare> oppShares = new List<OpportunityShare>();
for(Id i : oppIds)
{
   OpportunityShare os = new OpportunityShare(OpportunityId = i);
   os.OpportunityId = i; // *** ERROR - not writable ***
   os.OpportunityAccessLevel = 'Read/Write';
   os.UserOrGroupId = oppIdToLead.get(i).OwnerId;
   os.RowCause = 'Manual Sharing';
   oppShares.add(os);
}

Database.SaveResult[] result = Database.insert(oppShares, false);

Best Answer

This works in my org (I modified a little to allow for missing variables). Once I commented out the row cause, I was able to compile it...if you do that, does it still fail? If so, what's the error?

Set<Id> oppIds = new Set<Id> ();
Id newOwnerId;
List<OpportunityShare> oppShares = new List<OpportunityShare>();
for(Id i : oppIds) {
   OpportunityShare os = new OpportunityShare();
   os.OpportunityId = i; 
   os.OpportunityAccessLevel = 'Read/Write';
   os.UserOrGroupId = newOwnerId;
  // os.RowCause = 'Manual Sharing';
   oppShares.add(os);
}

Database.SaveResult[] result = Database.insert(oppShares, false);
Related Topic