When an Opportunity is marked as “Closed Lost,” this trigger ensures that the “Closed Lost Reason” field is populated. If it is empty, an error is displayed to the user.
Learn more from this YouTube playlist.
Solution:
trigger OpportunityTrigger on Opportunity (before update) {
if(Trigger.isUpdate){ if(Trigger.isBefore){
OpportunityTriggerHandler.populateClosedReason(Trigger.New , Trigger.oldMap);
}
}
}
public class OpportunityTriggerHandler { public static void
populateClosedReason(List oppList,
Map<Id,Opportunity> oldMap){ for(Opportunity opp:oppList){
if(opp.StageName == ‘Closed Lost’ && opp.StageName != oldMap.get(opp.Id).StageName
&&
opp.Closed_Lost_Reason__c == null){ opp.addError(‘Please
populate Closed Lost Reason’);
}
}
}
}