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
Dan Cline 1Dan Cline 1 

Apex Trigger to track opportunity products

Hi- I am trying to create an apex trigger to be able to track when products are added or removed from an opportunity  product page. Has anyone created one before? If so, would you mind sharing? Thanks!!
SARI4SARI4

 
I dont know what exactly you want to track on create and dlete of product.
If you want to track the count of PRoduct, then you can create Rollup Summary field on Opportunity to count the related products.
If there is something else then below is sample code.
trigger OpportunityLineItemTrigger on OpportunityLineItem ( after insert,after update,before delete){
////when product created/////////
 for (OpportunityLineItem  ol:trigger.new){

opportunity opp=[select id,name, field1__C,field2__c from opportunity where id=:ol.opportunity];

opp.field1__c=ol.createddate;
 update opp;
}

if(trigger.isdelete)
for (OpportunityLineItem  ol:trigger.new){

opportunity opp=[select id,name, field1__C,field2__c from opportunity where id=:ol.opportunity];

opp.field2__c=Today();   ////Delete date is todays date
 update opp;
}

}


 
Dan Cline 1Dan Cline 1
If Product A and Product B are added to an opportunity but then Product A is deleted, I want to be able to track that it was deleted.