Sunday, 16 September 2018

Trigger for All Rollup Summary calculations on Lookup Relation- Count, Minimum, Maximum, Sum and Average

This trigger will help you to update all the Rollup Summary calculations on Look up RelationShip.

Objects and Fields Information :
Contact (Object) --> Amount__c(Custom Field)
Account (Object) --> Sum__c (Custom Field)
                            --> Avg__c (Custom Field)
                           --> Min__c (Custom Field)
                           --> Max__c (Custom Field)
                           --> Count__c (Custom Field)

Here we are updating all the Account fields based on Contact's Amount__c Field data


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
trigger FullRollup on Contact (after insert, after update, after delete, after undelete){
   
    set<Id>Parent_set = new set<id>();
    List<Account>AccUpdateList = New List<Account>();
   
    if(trigger.isdelete || trigger.isupdate){
        for(Contact con : Trigger.old){
            Parent_set.add(con.AccountId);
        }
    }
   
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
        for(Contact con : Trigger.New){
            Parent_set.add(con.AccountId);
        }
    }
   
   
    for(AggregateResult aggcon : [Select AccountId,
                                      Count(Id)countt, Sum(amount__c)summ, avg(amount__c)avgg, min(amount__c)minn, max(amount__c)maxx
                                      From contact Where AccountId IN :Parent_set Group By AccountId]){
        Account Acc = New Account();
        Acc.Id     = (Id)aggcon.get('AccountId');
        Acc.Sum__c = (Decimal)aggcon.get('summ');
        Acc.Avg__c = (Decimal)aggcon.get('avgg');
        Acc.Min__c = (Decimal)aggcon.get('minn');
        Acc.Max__c = (Decimal)aggcon.get('maxx');
        Acc.Count__c = (Decimal)aggcon.get('countt');  
       
        AccUpdateList.add(Acc);    
       
    }
    Update AccUpdateList;
   
}

No comments:

Post a Comment