Skip to content

Instantly share code, notes, and snippets.

@sohalloran
Created April 30, 2018 13:39
Show Gist options
  • Save sohalloran/e46ebd2351f9ac983443850e4264e4f3 to your computer and use it in GitHub Desktop.
Save sohalloran/e46ebd2351f9ac983443850e4264e4f3 to your computer and use it in GitHub Desktop.
Opportunity Programatic Share - Reinsert Shares after ownership change
trigger OpportunityTrigger on Opportunity (before update) {
Set<Id> ownerChangeOppIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
if(opp.ownerId != Trigger.oldMap.get(opp.Id).OwnerId) {
ownerChangeOppIds.add(opp.Id);
}
}
if(!ownerChangeOppIds.isEmpty()) {
String oppShares = JSON.serialize([select opportunityId, UserOrGroupId, OpportunityAccessLevel, RowCause
from OpportunityShare
where RowCause='Manual' and opportunityId in: ownerChangeOppIds]);
OpportunityUtil.reinsertShares(oppShares);
}
}
public class OpportunityUtil {
@future
public static void reinsertShares(String os) {
List<OpportunityShare> newOppShares = new List<OpportunityShare>();
List<OpportunityShare> oppShares = (List<OpportunityShare>)JSON.deserialize(os, List<OpportunityShare>.class);
for(OpportunityShare oppShare : oppShares) {
newOppShares.add(new OpportunityShare(
opportunityId = oppShare.opportunityId,
UserOrGroupId = oppShare.UserOrGroupId,
OpportunityAccessLevel = oppShare.OpportunityAccessLevel,
RowCause = 'Manual'
));
}
if(! newOppShares.isEmpty()) {
Database.insert(newOppShares,false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment