I have a trigger on child object which updates the parent Obj field 'Qtyremaining' when there is a value in the child obj field 'Invoice_Quantity__c'. So the value of Parent "Qtyremaining = quantity - ip.Invoice_Quantity__c".

Now, the value in 'Invoice_Quantity__c' might change so I don't want my trigger object to subtract the new value entered in 'Invoice_Quantity__c' instead trigger has to calculate the difference of the old and new value of the 'Invoice_Quantity__c' field and then that difference should be subtracted. Not, sure how to achieve this in the trigger logic. Trigger code is attached.

trigger InVProd on Invoice_Product__c (after insert, after update) {

        decimal QtyRemaining;
        Set<String> OppProdIds = new Set<String>();
        List<OpportunityLineItem> updList =  new List<OpportunityLineItem>();
        for (Invoice_Product__c ip : Trigger.new) {
            if(ip.Opportunity_Product__c != null){

            Map<String, OpportunityLineItem> oliMap = new Map<String, OpportunityLineItem>();
            for(OpportunityLineItem oli : [Select Id, Quantity, Quantity_Remaining__c from OpportunityLineItem where Id in: OppProdIds]){
                String opp = oli.Id;
                oliMap.put(opp, oli);

            for(Invoice_Product__c ip : Trigger.New){
                Invoice_Product__c oldip = Trigger.oldMap.get(ip.Id);
                    if(oliMap.get(ip.Opportunity_Product__c).Quantity != null){
                        QtyRemaining = oliMap.get(ip.Opportunity_Product__c).Quantity;  


                    if(oliMap.get(ip.Opportunity_Product__c).Quantity != null && oldip.Invoice_Quantity__c != ip.Invoice_Quantity__c){
                        if (ip.Invoice_Quantity__c != null) {
                            QtyRemaining = QtyRemaining - ip.Invoice_Quantity__c; 


                        if(oliMap.get(ip.Opportunity_Product__c).Quantity_Remaining__c != QtyRemaining){
                            oliMap.get(ip.Opportunity_Product__c).Quantity_Remaining__c = QtyRemaining;


                update updList;

This looks like not specific to Salesforce but seeking help on the logic. If I understood correctly your question itself is having the answer.

Try to find the difference of old child and current child, then subtract that difference from the parent.Add one more line as below inside the if condition where you check if the Invoice_Quantity__c field value has been changed.

if(ip.Invoice_Quantity__c != null) {
    // add this line additionally and subtract from parent
    Decimal difference = oldip.Invoice_Quantity__c - ip.Invoice_Quantity__c;
    QtyRemaining = QtyRemaining - difference; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.