+ 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');
		}
	}
}