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
Raymond AireyRaymond Airey 

Automatically delete a product after Opportunity reaches certain amount?

HI All,

We have decided to include a 'Postage and Handling' fee for all opportunities that are created under $100.

By that I want any opportunity that is created and saved under $100 to automatically added an opportunity product of 'POSTAGEHANDLING' with a price of $9.95.

Currently I have a process in place that automatically adds the freight Product into every opportunity but I need to create an APEX trigger that will delete the same product once the opportunity is greater than $100.

I havent had much experience in Apex so any help would be greatly appreciated.

Ray
SandhyaSandhya (Salesforce Developers) 
Hi,

Below is the sample code to start over you need to change according to your requirements.
 
trigger proddeltrg on Opportunity(After update) {
    Set<Id> OppIds = new Set<Id>();
    Set<Id> sProdIds = new Set<Id>();
    List<Product2>  productsToDelete = new List<Product2>();
    for(Opportunity opp : trigger.Old) {
         if(opp.price>100)
       {
      oppIds.add(opp.Id);
        }
    }
    List<OpportunityLineitem> lstOppLineitem = [select id,PricebookEntry.Product2Id from OpportunityLineitem where OpportunityId IN: oppIds];
    for(OpportunityLineitem oli: lstOppLineitem){
        sProdIds.add(oli.PricebookEntry.Product2Id );
    }
    if(lstOppLineitem.size() > 0){
        delete lstOppLineitem;
    }
    productsToDelete = [SELECT Id,Name FROM product2 where Id IN: sProdIds];
    if(productsToDelete.size() > 0){
        delete productsToDelete;
    }
}
Please refer below link

https://developer.salesforce.com/forums/?id=906F000000094FlIAI

Hope this helps you!

If this helps you, please mark it as solved.

Thanks and Regards
Sandhya
Raymond AireyRaymond Airey
Hi Sandhya,

Thank you so much for this, its definetely a good start for me.

Looking at the code above, are you able to advise where I specify the ProductID that needs to be deleted from the Opportunity? Would I be setting the ID within these fields? "Set<Id> OppIds = new Set<Id>();" "Set<Id> sProdIds = new Set<Id>();"

Any help is very much appreciated,

Raymond
SandhyaSandhya (Salesforce Developers) 
Yes Raymond Airey, you are right.
Raymond AireyRaymond Airey

HI Sandhya,

I have tried a few different ways to insert the productID and all seem to be throwing exceptions.

I am trying to add "PricebookEntry.Product2.ISBN__c.01t6F000005BUc8" as the sProdIds.

Can you point me in the right direct of how the code may look?

Thanks,
Ray

SandhyaSandhya (Salesforce Developers) 
Hi,

Can you please post your code?

Thanks and Regards
Sandhya