+ Start a Discussion
Saurav nirwal 21Saurav nirwal 21 

Opportunity trigger

In Opportunity, If the stage is changed from another value to CLOSED_WON or CLOSED_LOST,populates the Close Date field with Today().
Jigar.LakhaniJigar.Lakhani
Hello,

Below is your opportunity trigger.

Apex Trigger
Trigger OpportuintyTrigger on Opportunity(BEFORE INSERT,BEFORE UPDATE){
	
	// Before Insert trigger
	if (Trigger.IsBefore && Trigger.isInsert) {
		for (Opportunity objOpportunity:Trigger.New) {
			if (objOpportunity.StageName == 'CLOSED_WON' || objOpportunity.StageName == 'CLOSED_LOST') {
				objOpportunity.CloseDate = System.Today();
			}
		}
	}
	
	// Before Update trigger
	if (Trigger.IsBefore && Trigger.isUpdate) {
		for (Opportunity objOpportunity:Trigger.New) {
			if (objOpportunity.StageName != Trigger.OldMap.Get(objOpportunity.Id).StageName && (objOpportunity.StageName == 'CLOSED_WON' || objOpportunity.StageName == 'CLOSED_LOST')) {
				objOpportunity.CloseDate = System.Today();
			}
		}
	}
	
}


Thanks & Cheers,
Jigar(pateljb90@gmail.com)
Ajay K DubediAjay K Dubedi
Hello Saurav,
This code update close date  
trigger changeStage on Opportunity (after update) {
    list<Opportunity> listOfOpportunity = [select Id,stageName,CloseDate  from Opportunity where ID IN : trigger.new];
    list<Opportunity>   tempListOfOpportunity=  new list<Opportunity>();
        for(Opportunity oppNew :listOfOpportunity)
        {
           if(oppNew.StageName!=trigger.oldMap.get(oppNew.id).stageName)
           {
              if(oppNew.stageName.equalsIgnoreCase('Closed Won') || oppNew.stageName.equalsIgnoreCase('Closed Lost'))
               {
                oppNew.CloseDate = Date.today();
                tempListOfOpportunity.add(oppNew);
                } 
           }
        }
        update tempListOfOpportunity; 
}
Thanks.

 
ManojjenaManojjena
Hi Saurav,

Try with belwo code it will help !! Please check your stage picklist value in code incase any mismatch please change .
Trigger OpportuintyTrigger on Opportunity(before insert,before update ){
	// Before Insert trigger
	if (Trigger.IsBefore && Trigger.isInsert) {
		for (Opportunity opp:Trigger.New) {
			if (opp.StageName == 'Closed own' || opp.StageName == 'Closed lost') {
				opp.CloseDate = System.Today();
			}
		}
	}
	
	// Before Update trigger
	if (Trigger.IsBefore && Trigger.isUpdate) {
		for (Opportunity opp:Trigger.New) {
			if ((Trigger.oldMap.get(opp.Id).StageName!='Closed own' ||Trigger.oldMap.get(opp.Id).StageName!='Closed lost') &&
     			(opp.StageName == 'Closed own' || opp.StageName == 'Closed lost')) {
				opp.CloseDate = System.Today();
			}
		}
	}
	
}

Let  me know if it helps 

Thanks 
Manoj