Tuesday, 7 July 2015

Rollup Summar trigger for a Lookup Relationship in Salesforce

      Here is the sample Roll-up Summary calculation trigger for Lookup relationship. The below trigger do a Sum Operation using Aggregate Query.

Parent: Account
Child: Contact
Logic: Update parent record field called Total__c with Sum of all related child records Amount__c field value.

  1. trigger TotalAmountTrigger on Contact (after insert, after update, after delete, after undelete)
  2. {
  3.     Set<Id> accountIds = new Set<Id>();
  4.     for(contact c: Trigger.isDelete? Trigger.old : Trigger.new){
  5.         if(c.AccountId != null)
  6.         {
  7.             accountIds.add(c.AccountId);
  8.         }
  9.     }  
  10.     List<Account> accList = new List<Account>();
  11.     for(AggregateResult currentAggResult:[SELECT AccountId accId, SUM(Amount__c) sumAmt FROM Contact  WHERE AccountId in:accountIds GROUP BY AccountId])
  12.     {
  13.         Account acc = new Account();
  14.         acc.Id = (Id)currentAggResult.get('accId');
  15.         acc.Total__c = (Decimal)currentAggResult.get('sumAmt');
  16.         accList.add(acc);
  17.         accountIds.remove((Id)currentAggResult.get('accId'));
  18.     }
  19.    
  20.     for(Id currAccId : accountIds)
  21.     {
  22.         Account acc = new Account();
  23.         acc.Id = currAccId;
  24.         acc.Total__c = null;
  25.         accList.add(acc);
  26.     }
  27.     update accList;
  28. }


1 comment:

  1. Since there are two objects in the above scenario.
    What if there is self relationship to the object itself. Say for example there is a self relationship on account object and 1 account can have multiple child account. In that case how to use the fields of child account??
    Thanks in advance!!

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...