+ Start a Discussion
AlecSAlecS 

Trigger on Opportunity - Saving with Stage Close Won

I have a trigger that does some work when the opportunity is closed with stage=close won. But my code also checks to make sure that if I am editing an opportunity that is saved with stage=close won (that is trigger.old has stage = close won) then it should not carry out the task.

 

Trigger createRenewalOpp on opportunity(after update){

    List<Opportunity> oppList = new List<Opportunity>();
    
    //making sure that the opportunity is not already closewon
    for(Opportunity p : trigger.old) {
          if(p.stageName !='Closed Won' ){

//execute code
}
}
}

 

The problem with above code is that if I create a new opportunity and close it starught away with stage = close won (meaning trigger.old has no value) then the code following the "if" statement does not execute.

 

How can I check to create an exception for such a scenario?

 

Thank you!

 

Ritesh AswaneyRitesh Aswaney

For starters, that would trigger an after insert event rather than an after update event, so you would need to add 'after insert' to your trigger declaration.

 

You will then need to iterate over trigger.new rather than trigger.old, as there will be no trigger.old in an after insert trigger

 

You can compare Stage by pulling out the Opp from the trigger.oldMap, so

 

if( (trigger.oldMap(opp.Id).StageName != 'Closed Won'  || trigger.isInsert) && opp.StageName = 'Closed Won'))