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
travis.truetttravis.truett 

Access Opportunity Close Date from Opp Line Item Trigger

I'm writing a trigger on OpportunityLineItem, but I need to access the Close Date of the OpportunityLineItem's associated Opportunity. Is there a way to do this?
sfdcfoxsfdcfox
Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>();
for(OpportunityLineItem record: Trigger.new) {
    opportunities.put(record.OpportunityId, null);
}
opportunities.putAll([SELECT CloseDate FROM Opportunity WHERE Id in :opportunities.keySet()]);
for(OpportunityLineItem record: Trigger.new) {
     Opportunity thisLineItemOpp = opportunities.get(record.OpportunityId);
      // thisLineItemOpp.CloseDate is the close date you're looking for
}
This is a fairly standard "aggregate-query-update" style design.
Amit Chaudhary 8Amit Chaudhary 8
Hi Travis,

Please try below code. I hope this will help you:-
trigger OpportunityLineItemsTrigger on OpportunityLineItem ( before insert, before update) 
{
	Set<string> setOppId = new Set<String>();
	for( OpportunityLineItem opli : trigger.New )
    {
		setOppId.add(opli.opportunityid);
	}
	
	if( setOppId.size() > 0 )
	{
		Map<Id,Opportunity> mapOpp = new  Map<Id,Opportunity> ([select id ,CloseDate from Opportunity where id in :setOppId ] );
		
		for( OpportunityLineItem opli : trigger.New )
		{
			if(mapOpp.containsKey(opli.opportunityid) )
			{
				Opportunity opp = mapOpp.get(opli.opportunityid);
				System.debug('----------->'+opp.CloseDate);
				// opli.CloseDate__C = opp.CloseDate; // Add your logic here
			}
		}
	}

}

Please let us know if this will help you.

Thanks,
Amit Chaudhary
Terence_ChiuTerence_Chiu
Travis, if you are fine with using a custom formula field you can create a cross object formula to pull the opportunity's close date. From the Opportunity Product object, create a new formula field of type Date and use the following as the formula:

Opportunity.CloseDate

For instance if you have an Opportunity Product custom field called Opp_Close_Date__c you can access it directly from the opportunitylineitem object from the trigger.
 
for(OpportunityLineItem oli : trigger.new){
      Date oppCloseDate = oli.Opp_Close_Date__c;
}