function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nadeem Uddin 2Nadeem Uddin 2 

Trigger at opportunity when stage changed from Closed won to Closed lost

Hi

I want my trigger to check a custom checkbox field (called Cancelled) when my opportunity stage changes from closed won to closed lost.
I know we can get that information from Opportunity Stage History reports also we can create a workflow rule (below)

1 AND(
2 ISCHANGED(IsWon),
3 PRIORVALUE(IsWon),
4 IsClosed,NOT(IsWon))

From a knowledge perspective how can I achieve this via trigger?

Thanks
Best Answer chosen by Nadeem Uddin 2
Srinivas SSrinivas S
Please find the following solution -
trigger OpportunityTrigger on Opportunity (before update) {
    for(Opportunity opp : trigger.new) {
        if(opp.StageName == 'Closed Lost' && trigger.oldMap.get(opp.Id).StageName == 'Closed Won') 
            opp.Cancelled__c = true;
    }
}

------------
Thanks,
Srinivas
- Please mark as solution if your problem is resolved.

All Answers

Mina Michel GorgyMina Michel Gorgy
Hi Nadeem,

You can use the trigger.old to get the old values. So in you case, you'll get the checkbox "Cancelled" and the PRIORVALUE of the stage... The compare with the trigger.new values which will contain the updated stage of the opportunity.

Then you'll add your logic to add an error message for the incorrect opportunities.

Please do not forget to mark this as the correct answer, if it suits you.
Srinivas SSrinivas S
Please find the following solution -
trigger OpportunityTrigger on Opportunity (before update) {
    for(Opportunity opp : trigger.new) {
        if(opp.StageName == 'Closed Lost' && trigger.oldMap.get(opp.Id).StageName == 'Closed Won') 
            opp.Cancelled__c = true;
    }
}

------------
Thanks,
Srinivas
- Please mark as solution if your problem is resolved.
This was selected as the best answer
Himanshu Chhabra 9Himanshu Chhabra 9
trigger CheckCustomCheckbox on Opportunity (before Update) {
        for(Opportunity Opp:trigger.new){
        //Access old Records of opportunity using oldMap
        Opportunity oldVal=Trigger.oldMap.get(Opp.Id);
     
         Boolean OldCloseLost=oldVal.StageName.equals('Closed Won');
         Boolean newCloseLost=Opp.StageName.equals('Close Lost');
         
         if(OldCloseLost && newCloseLost){
             Opp.MyLightningP__Cancelled__c=true;
         
         }
        
        }
}

Thanks
Himanshu

Please maek it as the best solution if it helped you in resolving the problem