1

Every time I update/delete a detail record, my custom field from master record that sums up all quantities of detail records does not update. It just works after insert.

trigger updateField on Sample2__c (after insert, after update, after delete) {
    List<Sample1__c> s1List = new List<Sample1__c>();
    Set<Id> set2 = new Set<Id>();

    if(Trigger.isAfter) {

        if(Trigger.isInsert || Trigger.isUpdate) {

            for(Sample2__c s2 : Trigger.new) {
                set2.add(s2.Sample1__c);
            }

            Decimal sum;

            for(Sample1__c s1 : [SELECT Id, Name, (SELECT Id, Name, Quantity__c FROM Sample2__r) FROM Sample1__c WHERE ID IN: set2]) {

                sum = 0;

                for(Sample2__c ss2 : s1.Sample2__r) {
                    sum += ss2.Quantity__c;
                }

                s1.Total__c = sum;
                s1List.add(s1);
            }
            update s1List; 

        }    

        if(Trigger.isDelete) {
            for(Sample2__c s2 : Trigger.old) {
                set2.add(s2.Sample1__c);
            }
        }   

    } 
}
3
  • Can you please mention the exact problem that you are facing and also try to add Trigger.isAfter in the If condition of both the IF statement. So you are making sure you are calling that code only after insert/update/delete
    – RCS
    Nov 29, 2016 at 8:50
  • @RCS My problem is that the value of Total__c field from Sample1__c object does not update whenever I update/delete a Sample2__c record. Only the value changes during after insert event Nov 29, 2016 at 9:01
  • if its master detail then you can use Roll up summary fields. Nov 29, 2016 at 9:27

1 Answer 1

0

Try below code if the business logic is correct. Code is not compiled

trigger updateField on Sample2__c (after insert, after update, after delete) {
    Set<Id> set2 = new Set<Id>();
    if(Trigger.isAfter && (trigger.isInsert || trigger.isUpdate)) {
        for(Sample2__c s2 : Trigger.new) {
            set2.add(s2.Sample1__c);
        }
    } else if(trigger.isAfter && trigger.isDelete){
        for(Sample2__c s2 : Trigger.old) {
            set2.add(s2.Sample1__c);
        }   
    }       
    if(!set2.isEmpty()) {
        TriggerHandler.funTotalSum(set2);
    }
}

public with sharing class TriggerHandler {

    public static void funTotalSum(Set<Id> set2) {
        Decimal sum;
        List<Sample1__c> s1List = new List<Sample1__c>();
        for(Sample1__c s1 : [SELECT Id, Name, (SELECT Id, Name, Quantity__c FROM Sample2__r) FROM Sample1__c WHERE ID IN: set2]) {

            sum = 0;

            for(Sample2__c ss2 : s1.Sample2__r) {
                sum += ss2.Quantity__c;
            }

            s1.Total__c = sum;
            s1List.add(s1);
        }
        update s1List;
    }
}
1
  • Why not just do and aggregate query. Much simple
    – Eric
    Nov 29, 2016 at 9:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .