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 = string.valueOf(ar.get('accountId'));
Account thisAccount = new Account(Id = thisAccountId);    
thisAccount.Total_Age__c = double.valueOf(ar.get('totalAge'));
updateAccounts.add(thisAccount);
}
update updateAccounts;

Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page