Trigger to sum all the child record field and storing it in another object field in Salesforce


Consider the below Scenario
Quote and Structure__c --> Master Detail relationship
Quote and Bigmachine__c --> Lookup relationship
Structure__c and Bigmachine__c --> Lookup relationship

We have to calculate total scope on Big Machine object, which should be the sum of all scope in Structure__c object.


Sample Trigger:

trigger Structure_AIUD on Structure__c (after insert, after update) {
    Set<Id> quoteIds = new Set<Id>();
    List<Structure__c> structList = new List<Structure__c>();
    Map<Id, List<Structure__c>> quoteIdStructListMap = new Map<Id, List<Structure__c>>();
    List<Big_Machine__c> bigMachineList = new List<Big_Machine__c>();
    Map<Id, Double> quoteIdTotalScopeMap = new Map<Id, Double>();
    
    for(Structure__c struct : trigger.New) {
        quoteIds.add(struct.Quote__c);
    }
    
    structList = [SELECT Id, Scope__c, Quote__c FROM Structure__c WHERE Quote__C IN : quoteIds];
    bigMachineList = [SELECT Id, Total_Scope__c, Quote__c FROM Big_Machine__c WHERE Quote__C IN : quoteIds];
    
    if(bigMachineList.size() > 0) {
        if(structList.size() > 0) {
            for(Structure__c struct : structList) {
                if(!quoteIdStructListMap.containsKey(struct.Quote__c)) {
                    quoteIdStructListMap.put(struct.Quote__c, new List<Structure__c>());
                }
                quoteIdStructListMap.get(struct.Quote__c).add(struct);
            }    
            
            for(Id quoteId : quoteIdStructListMap.keySet()) {
                List<Structure__c> tempStructList = new List<Structure__c>();
                tempStructList = quoteIdStructListMap.get(quoteId);
                Double tempTotalScope = 0;
                for(Structure__c struct : tempStructList) {
                    tempTotalScope = tempTotalScope + struct.Scope__c;
                }
                quoteIdTotalScopeMap.put(quoteId, tempTotalScope);
            }           
        }
        for(Big_Machine__c bigMachine : bigMachineList) {
            bigMachine.Total_Scope__c = quoteIdTotalScopeMap.get(bigMachine.Quote__c);
        }
        update bigMachineList;
    }
}

1 comment: