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
Newbie  2014Newbie 2014 

How to access the ID stored in a lookup field on a just deleted record using from Trigger.old?

Hello: I am new to apex coding, would greatly appreciate some help with the following problem:
In an “after delete” trigger on opportunitylineitem object I have to access the values or stored IDs for two lookup fields -  ‘opportunity” & “product2”. I can access all other field types like quantity, totalprice etc. using trigger.old, but for those lookup fields, I am getting NULLs. Here is my code:

trigger InvoiceLineItemDeletion on OpportunityLineItem (after delete) {

for (OpportunityLineItem o_l : trigger.old) {

      Opportunity parentOpportunity = o_l.Opportunity; \\ “o_l.Opportunity” returns NULL, please specify the correct format        
      Product2 product2Used = o_l.product2; \\ “o_l.product2” returns NULL

      String qty = o_l.quantity \\ “o_l.quantity” returns correct value
      String parentOpp = [select Name from opportunity where Id =: parentOpportunity.id].Name; \\One more question: is this the correct statement using
                                                                                                                                                                          \\ SOQL to access the parent opportunity name?
      String prodUsed = [select Name from Product2 where Id = :Product2Used.id].Name;
     ……
     …..
}     

      
Thanks very much in advance.
Best Answer chosen by Newbie 2014
JonathanBaltzJonathanBaltz
Hi there,
If the object that you are using in this trigger is OpportunityLineItem, that object acually has standard fields for the relationships you are looking for.  Try updating the code: 
  Opportunity parentOpportunity = o_l.OpportunityId;
   Product2 product2Used = o_l.Product2Id;

Hope that helps and works.

All Answers

JonathanBaltzJonathanBaltz
Hi there,
If the object that you are using in this trigger is OpportunityLineItem, that object acually has standard fields for the relationships you are looking for.  Try updating the code: 
  Opportunity parentOpportunity = o_l.OpportunityId;
   Product2 product2Used = o_l.Product2Id;

Hope that helps and works.
This was selected as the best answer
Newbie  2014Newbie 2014
Jonathan: Thanks so very much, that worked and helps like anything. Have a good weekend!
JonathanBaltzJonathanBaltz
Glad it worked.  Since it did work, can you mark my response as the solution and the question as solved.  Thank you, and I hope you have a good weekend as well.
Newbie  2014Newbie 2014
Just did, thanks again