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
Force.platformForce.platform 

Trigger on opporrunity

i have to write trigger for,
When Opportunity ‘Close Date’  is populated, should not be less than current date and time. If it is less, show an appropriate error msg.
how to do this?

 
Best Answer chosen by Force.platform
GouthamGoutham
Hi Arati Chirame,

Use below code
trigger opportunityTrigger on Opportunity (before insert , before update){
	if(trigger.isBefore){
		if(trigger.isInsert){
			opportunityTriggerHandler.dateValidation(trigger.new,null);
		}
		if(trigger.isUpdate){
			opportunityTriggerHandler.dateValidation(trigger.new,trigger.oldMap);
		}
	}
}
 
public class opportunityTriggerHandler{
	public static void dateValidation(list<Opportunity>oppList , Map<id,Opportunity>oldMap){
		set<id> oppIds = new set<id>();
		boolean isInsert = (oldMap==null);
		for(Opportunity opp : oppList){
			if((isInsert && opp.CloseDate != null) || (!isInsert && opp.CloseDate != null && opp.CloseDate != oldMap.get(opp.id).CloseDate))
				if(opp.CloseDate <= system.now())
					opp.addError('Error Message');
		}
	}
}