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
Vaibhav Parashar 2Vaibhav Parashar 2 

Trigger to delete a record in product when a field in opportunity is changed?

Trigger to delete a record in product when a field in opportunity is changed?
VineetKumarVineetKumar
Let me know if this helps
trigger deleteProduct on Opportunity (before delete) {
    Set<Id> opportunityIdSet = new Set<Id>();
    Set<Id> productIdSet = new Set<Id>();
    List<Product2>  deleteProductList = new List<Product2>();
    for(Opportunity thisOpportunity : trigger.Old) {
      opportunityIdSet.add(thisOpportunity.Id);
    }
    for(OpportunityLineitem thisOli: [SELECT Id, PricebookEntry.Product2Id FROM OpportunityLineitem WHERE OpportunityId IN: opportunityIdSet]){
        productIdSet.add(thisOli.PricebookEntry.Product2Id );
    }
    if(!opportunityLineItemList.isEmpty()){
        delete opportunityLineItemList;
    }
    deleteProductList = [SELECT Id, Name FROM product2 WHERE Id IN: productIdSet];
    if(!deleteProductList.isEmpty()){
        delete deleteProductList;
    }
}
Vaibhav Parashar 2Vaibhav Parashar 2
Hi Vineet, this did not work. I want to delete all the Product records related to opportunity, whenever PriceBook Lookup is changed. This is the code that i have. 

The only problem is I am unable to delete Product records in Before update part.

trigger addProductonPriceBookChange on Opportunity (after insert,before update,after update) {

for(Opportunity opp : Trigger.new){


if( Trigger.isAfter && Trigger.isInsert )
    {
    //List that Queries the fields of opportunity

 List<Opportunity> oppList = New List<Opportunity>();

oppList = [Select id,name,Pricebook2.id,Pricebook2.Name from Opportunity where id =: opp.id];
List<PriceBookEntry> pbE = [Select id,name,Pricebook2Id,Pricebook2.Name from PriceBookEntry where Pricebook2Id =: opp.Pricebook2Id ];


    List<OpportunityLineItem> proList = New List<OpportunityLineItem>();
        
            for(PriceBookEntry pb : pbE){
        OpportunityLineItem p = new OpportunityLineItem();

                p.PricebookEntryId=pb.id;
                p.Quantity=1;
                p.OpportunityId=opp.Id;
                p.UnitPrice=100;
            
                proList.add(p);
}
                  insert proList;
            system.debug('The values present in proList is ------------->' +proList);

       system.debug(' Is Executed after Insert ');
        
        
    }
    else if ( Trigger.isBefore && Trigger.isUpdate )
    {
        if(system.trigger.OldMap.get(opp.Id).Pricebook2Id != system.trigger.NewMap.get(opp.Id).Pricebook2Id){
          system.debug(' Price Book was Changed ');
          
     List<PriceBookEntry> pbE1 = [Select id,name,Pricebook2Id,Pricebook2.Name from PriceBookEntry where Pricebook2Id =: system.trigger.NewMap.get(opp.Id).Pricebook2Id];
        system.debug(' -----------The price book entry are --- ' +pbE1);
        
        List<OpportunityLineItem> proList1 = New List<OpportunityLineItem>();
          proList1 = [Select id, name from OpportunityLineItem where OpportunityId =: opp.Id ];
          
            system.debug(' -----------The line items are --- ' +proList1);
            
          
          
         
       
           
    }


}else if ( Trigger.isAfter && Trigger.isUpdate )
    {
        if(system.trigger.OldMap.get(opp.Id).Pricebook2Id != system.trigger.NewMap.get(opp.Id).Pricebook2Id){
          
         List<Opportunity> oppList = New List<Opportunity>();

oppList = [Select id,name,Pricebook2.id,Pricebook2.Name from Opportunity where id =: opp.id];
List<PriceBookEntry> pbE = [Select id,name,Pricebook2Id,Pricebook2.Name from PriceBookEntry where Pricebook2Id =: opp.Pricebook2Id ];


    List<OpportunityLineItem> proList = New List<OpportunityLineItem>();
        
            for(PriceBookEntry pb : pbE){
        OpportunityLineItem p = new OpportunityLineItem();

                p.PricebookEntryId=pb.id;
                p.Quantity=1;
                p.OpportunityId=opp.Id;
                p.UnitPrice=100;
            
                proList.add(p);
}
                  insert proList;
            system.debug('The values present in proList is ------------->' +proList);
       
           
    }


}
}
}
VineetKumarVineetKumar
The abve code has been structured in a very bad way, which is bound to fail for bulk records, this trigger is not at all bulkified.
You don't write SOQL queries inside a for loop and perform any DML operation inside for loop, as it is bound to hit salesforce limit.

https://developer.salesforce.com/page/Best_Practice%3A_Bulkify_Your_Code

Also, your delete code should run in the after context not on before context.
Your code should look something like this:
if(Trigger.isAfter && Trigger.isUpdate)
	Map<Id, OpportunityLineItem> opportunityOliMap = new Map<Id, OpportunityLineItem>();
	for(OpportunityLineItem thisOli : [SELECT Id, Name, OpportunityId, PricebookEntry.Product2Id FROM OpportunityLineItem WHERE OpportunityId IN: Trigger.New]){
		opportunityOliMap.put(OpportunityId, thisOli);
	}
	List<OpportunityLineItem> deleteOli = new List<OpportunityLineItem>();
	for(Opportunity opp : Trigger.new){
		if(system.trigger.OldMap.get(opp.Id).Pricebook2Id != system.trigger.NewMap.get(opp.Id).Pricebook2Id){
			system.debug(' Price Book was Changed ');
			if(opportunityOliMap.containsKey(opp.Id)){
				deleteOli.add(opportunityOliMap.get(opp.Id));	
			}			
		}
	}
	if(!deleteOli.isEmpty()){
		delete deleteOli;
	}
}
Let me know if you need any help in writing the trigger.