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 accids=new Set(); List acctoupdate=new List(); Map> AccountMap=new Map>(); 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 ) { accids.add(aa.parentId); } } try { // Query the childs records which are being updated along with all the childs of the parents record to which it is associated List 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) { if(AccountMap.containsKey(aa.parentId)) { List tempList = AccountMap.get(aa.parentId) ; tempList.add(aa); AccountMap.put(aa.parentId , tempList) ; } else { AccountMap.put(aa.parentId , new List{aa}) ; } } ///Processing // 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){ if(userCaseMap.containsKey(ii)) { Decimal SA=0; Decimal CA=0; List allaccountofid = AccountMap.get(ii) ; For(Account allacc:allaccountofid) { SA+=allacc.Standard_Application__c; CA+=allacc.Custom_Application__c; } Account aid=new Account(id=ii,Standard_ Application_Summary__c=SA, Custom_Application_ Summary__c=CA); acctoupdate.add(aid); } }