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
alextc78alextc78 

How to get Product Name on OpportunityLineItem Delete in Apex Trigger?

I'm trying to create a very simple Apex trigger that will do different actions on an Opportunity Product deletion, depending on which product it is.
I"m encountering a very basic problem and I'm sure I'm just missing something simple here? any guidance would be greatly appreciated.

Apex Trigger:
trigger OppProdDelete on OpportunityLineItem (after delete) {
     for(OpportunityLineItem prod : Trigger.Old) {
          system.debug('OppProdDelete: Product2.Name=' + prod.Product2.Name); // option 1 - gives me null
         system.debug('OppProdDelete: Product2.Name=' + prod.PricebookEntry.Product2.Name); // option 2 - gives me null
}
I tried both option 1 and 2 above to get the product name so I can take the appropriate actions, but both return NULL. How do I reference the product name?

Thanks,
​​​​​​​Alex
Best Answer chosen by alextc78
MKRMKR
Hi,

Related records are not directly available in the trigger. Instead you need to query them:
 
trigger OppProdDelete on OpportunityLineItem (after delete) {
     Set<Id> productIDs = new Set<Id>();
     for(OpportunityLineItem prod : Trigger.Old) {
          productIDs.add(prod.Product2Id);
     }
     Map<Id, Product2> productMap = new Map<Id, Product>([SELECT Id, Name FROM Product2 WHERE Id IN :productIDs);
     for(OpportunityLineItem prod : Trigger.Old) {
          Product2 relatedProduct = productMap.get(prod.Product2Id);
          System.debug(productMap.get(prod.Product2Id).Name); // This is not null
     }
}
Regards,
MKR

All Answers

MKRMKR
Hi,

Related records are not directly available in the trigger. Instead you need to query them:
 
trigger OppProdDelete on OpportunityLineItem (after delete) {
     Set<Id> productIDs = new Set<Id>();
     for(OpportunityLineItem prod : Trigger.Old) {
          productIDs.add(prod.Product2Id);
     }
     Map<Id, Product2> productMap = new Map<Id, Product>([SELECT Id, Name FROM Product2 WHERE Id IN :productIDs);
     for(OpportunityLineItem prod : Trigger.Old) {
          Product2 relatedProduct = productMap.get(prod.Product2Id);
          System.debug(productMap.get(prod.Product2Id).Name); // This is not null
     }
}
Regards,
MKR
This was selected as the best answer
alextc78alextc78
Many thanks MKR!
I don't do much Apex coding, maybe once a year, and I seem to fall into this trap often. I'm surprised I didn't get an error that I was trying to access a related record, which would have made it obvious. again, thanks.