You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Rollup on Self Relationship in Salesforce

The requirement here is like “Need to roll up the things in child records to parent record ” – Self Relationship

When I started to write the code, I feel quite easy to achieve this task , Later I came to know that the code I wrote would work only on single record. I didn’t find the way of bulkify the code for a while. Since the case is like parent record will have many childs and the trigger is supposed to handle many parent records which will be having many child records.

At later point of time , i came across the idea of having Map (collection) to process this sort of complexity .

Let me share the code here:

trigger AccoutApplications on Account ( after update) 
 Set<Id> accids=new Set<Id>();
 List<Account> acctoupdate=new List<Account>();
 Map<Id , List<Account>> AccountMap=new Map<Id , List<Account>>();
 For(Account aa : Trigger.New)
 Account oldacc= Trigger.oldMap.get(aa.Id);
 Account newacc= Trigger.newMap.get(aa.Id);
// Get the parent records whose one of the child records being updated
 if( aa.parentId!=null )
 // Query the childs records which are being updated along with all the childs of the parents record to which it is associated 
 List<Account> Accountts = [ select id,Standard_Application__c,Custom_Application__c,parentId from Account where ParentId IN :accids];
 // Map collection ( Id , List of records )
// Parent Record Id as key and List of child records as the value 
  For(Account aa: Accountts)
  List<Account> tempList = AccountMap.get(aa.parentId) ;
  AccountMap.put(aa.parentId , tempList) ;  
   AccountMap.put(aa.parentId , new List<Account>{aa}) ;  
// Pulling out the all the child records of the parent and update the parent record ,and iterate over all the parent records which is having mutiple child records
  For(Id ii:accids){
Decimal SA=0;
  Decimal CA=0;
  List<Account> allaccountofid = AccountMap.get(ii) ; 
  For(Account allacc:allaccountofid)
  Account aid=new Account(id=ii,Standard_Application_Summary__c=SA,Custom_Application_Summary__c=CA);