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
elossoelosso 

Getting Opportunity Name from OpportunityLineItem in trigger

I have a trigger in Opportunity Product that creates new record in a custom Object (Impressions) once whenever a certain type of Opportunity Product is added to an Opportunity.

 

The Impressions Object has a Lookup Field, called Opportunity Name, linked to the Opportunity Object. I'd like to populate Opportunity Name with the Name of the Opportunity (as listed in the Oportunituy Object); however, my code does not seem to be able to do that. At the moment, it does not populate with anything at all. Any help would be appreciated, thank you!

 

Here is my code... issue is that the following line does not appear to pass the Name to the Opportunity_Name__c field.

i.Opportunity_Name__c = o.Opportunity.Name;

 

trigger createNewImpression on OpportunityLineItem (after insert) {

    List <Impressions__c> impToInsert = new List <Impressions__c> ();

    for (OpportunityLineItem o : Trigger.new) {
        
        if (o.Product_Family__c == 'Impression') {     
            
            Impressions__c i = new Impressions__c ();          
            
            i.Opportunity_Name__c = o.Opportunity.Name;
            i.Bill_Date__c = o.ServiceDate;
            i.Expected_Impressions__c = o.Quantity;
            i.Predicted_Revenue__c = o.TotalPrice;
            
        impToInsert.add(i);
        
        }
        
    }
    
    insert impToInsert;

}

 

 

sandeep@Salesforcesandeep@Salesforce

It is common problem for many developers. Actually there is a concept that you can not fetch fields of parnet obejct of your object (here opportunity line item) in Trigger.New.

 

so for this you need to query these fields as below :

 

trigger createNewImpression on OpportunityLineItem (after insert) {

    List <Impressions__c> impToInsert = new List <Impressions__c> ();

    for (Opportunitylineitem o : [select id , Opportunity.Name from Opportunitylineitem where id in Trigger.New]) {
        
        if (o.Product_Family__c == 'Impression') {     
            
            Impressions__c i = new Impressions__c ();          
            
            i.Opportunity_Name__c = o.Opportunity.Name;
            i.Bill_Date__c = o.ServiceDate;
            i.Expected_Impressions__c = o.Quantity;
            i.Predicted_Revenue__c = o.TotalPrice;
            
        impToInsert.add(i);
        
        }
        
    }
    
    insert impToInsert;

}

 

}