I wrote some code on Opportunity that compares new values to OldMap values and should execute a record clone only if the record was JUST Closed Lost
. I'm not sure if my interpretation of OldMap is wrong, or if there is something else in my code explaining why it would be running this code twice during recursion scenarios, but the end result is that I am getting 2 new opportunity clones instead of one.
Question: Does oldMap maintain the original record values, even throughout multiple loops through the order of execution due to recursion? Or should the oldMap values change as the record goes through the loop multiple times? I know I can solve recursion with an ID set or map to check if the record has already run through the code, but I thought that oldMap comparisons would serve a similar purpose if written correctly.
I searched and could not find a similar question, and the Trigger class documentation doesn't explicitly define if/when oldMap changes:
oldMap
A map of IDs to the old versions of the sObject records.
This map is only available in update and delete triggers.
Code for Reference:
protected override void beforeUpdate(){
system.debug('Start MasterOpportunityTrigHdlr IsUpdate - Before');
Opportunity oldOpp;
String stage, stageReason;
String oldStage, oldStageReason;
Boolean newClose;
Boolean transferred;
Opportunity clonedOpp;
Id originalOwner;
Id newOwner;
Date assignedDate;
List<Opportunity> OppsToInsert = new List<Opportunity>();
For(Opportunity opp : newList){
stage = opp.StageName;
stageReason = opp.Closed_Lost_Options__c;
oldOpp = oldMap.get(opp.Id);
oldStage = oldOpp.StageName;
oldStageReason = oldOpp.Closed_Lost_Options__c;
assignedDate = System.today();
originalOwner = opp.OwnerId;
newClose = false;
transferred = false;
if(CLOSED_LOST.equalsIgnoreCase(stage) && !CLOSED_LOST.equalsIgnoreCase(oldStage)){
newClose = true;
if(TRANSFER.equalsIgnoreCase(stageReason))
transferred = true;
newOwner = opp.Transfer_To__c;
}
if(newClose && transferred){
clonedOpp = OpportunityUtil.cloneOpportunity(oldOpp);
clonedOpp.OwnerId = newOwner;
clonedOpp.Last_Assigned_Date__c = assignedDate;
clonedOpp.Transferred_From__c = originalOwner;
OppsToInsert.add(clonedOpp);
}
}
if(!OppsToInsert.isEmpty()){
Database.insert(OppsToInsert);
}
system.debug('End MasterOpportunityTrigHdlr IsUpdate - Before');
}