Posts

Showing posts from April, 2019

Rollup value from Child object To Parent Object Using Aggregate Result Query

Requirement: Update Total Age on Account from contact. Write a trigger on Contact, When Contact record will insert with age value update the total age on Account of child contacts, Create Age number field on Contact object Create Total Age number field on Account Object trigger updateTotalAgeonAccount on Contact (after insert,after delete ,after update) { set<Id> accountIds = new set<Id>(); list<account> updateAccounts = new list<account>(); if(Trigger.isUpdate ||Trigger.isInsert) { for(contact c : trigger.new) { accountIds.add(c.accountid); } } if(Trigger.isDelete) { for(contact c : trigger.old) { accountIds.add(c.accountid); } } //run the query to sum the data AggregateResult[] totalAges= [select  SUM(age__c)totalAge,accountId  From Contact where accountId IN:accountIds group by accountId]; System.debug('totalAges@@@'+totalAges); for(AggregateResult ar: totalAges) { Id thisAccountId