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
Tejaswini LambeTejaswini Lambe 

AfterDelete trigger on opportunitylineitem

Hi Team,
I want to write a trigger on delete of opportunity line items. I have a following requirement:
Opportunity Fields: Approval Status, Discount
If an opportunity line item is deleted, when the opportunity approval status is approved, and deletion results in increase in discount (compared to discount before deleting opportunitylineitem), the opportunity approval status should be chnaged to 'Unapproved.'
I need immediate help. Any pointers/feedback are appreciated.
Morgan GoughMorgan Gough
Hello, Create an Apex trigger on the OpportunityLineItem object that fires on the before delete event.
In the trigger, query the related Opportunity records for the deleted OpportunityLineItems using the OpportunityId field.
Iterate through the queried Opportunity records and check if the Approval Status is 'Approved'.
If the Approval Status is 'Approved', compare the Discount value of the OpportunityLineItem being deleted with the existing Discount value on the Opportunity.
If the Discount value of the OpportunityLineItem being deleted is greater than the existing Discount value on the Opportunity, update the Approval Status of the Opportunity to 'Unapproved'.
Save the modified Opportunity records.  https://www.mykfcexperience.website/
SubratSubrat (Salesforce Developers) 
Hello Tejaswini ,

Please try with the below code and let me know if you have any further questions ahead .
trigger OpportunityLineItemTrigger on OpportunityLineItem (before delete) {
    // Collect the Opportunity Ids for the deleted Opportunity Line Items
    Set<Id> opportunityIds = new Set<Id>();
    Map<Id, Decimal> originalDiscounts = new Map<Id, Decimal>();
    
    for (OpportunityLineItem oli : Trigger.old) {
        opportunityIds.add(oli.OpportunityId);
        originalDiscounts.put(oli.OpportunityId, oli.Discount);
    }
    
    // Query the related Opportunities
    Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>(
        [SELECT Id, Approval_Status_c, Discount_c
         FROM Opportunity
         WHERE Id IN :opportunityIds]);
    
    // Iterate through the deleted Opportunity Line Items
    for (OpportunityLineItem oli : Trigger.old) {
        Opportunity opp = opportunities.get(oli.OpportunityId);
        
        // Check if the Opportunity is approved and if the deletion increases the discount
        if (opp.Approval_Status__c == 'Approved' && oli.Discount > originalDiscounts.get(oli.OpportunityId)) {
            opp.Approval_Status__c = 'Unapproved';
        }
    }
    
    // Update the modified Opportunities
    update opportunities.values();
}

If this helps , please mark this as Best Answer.
Thank you.