Please find the sample code below and tweak it as per the requirement.
trigger totalAmount on Account (after update) {
// Will need to use a Run Once technique so it doesn't get recursively called - I can post something on that if needed.
// Get parents of accounts that fired the trigger
set<id> parentIds = new set<id>();
for(Account a :trigger.new) {
if(a.ParentId != null) {
parentIds.add(a.ParentId);
}
}
// Get children of those parents & sum amount
list<AggregateResult> childARs = [SELECT ParentId parentId, SUM(Amt__c) amtTotal
FROM Account
WHERE ParentId in :parentIds
GROUP BY parentId
map<id,decimal> mParentAmounts = new map<id,decimal>();
for (aggregateResult ar :childARs) {
mParentAmounts.put(string.valueOf(ar.get('parentId')), decimal.valueOf(string.valueof(ar.get('amtTotal'))));
}
// Now get the Grandparent Ids
list<Account> parents = new list<Account>([SELECT id,parentId FROM Account WHERE Id IN :mParentAmounts.keyset()]);
set<id> grandParentIds = new set<id>();
for(Account a :parents) {
grandParentIds.add(a.parentId);
}
// Get all the children of the grandparents & sum totals, replacing the total in the mParentAmounts map
list<Account> parents2 = new list<Account>([SELECT id,parentId,Amt__c FROM Account WHERE id IN :grandParentIds]);
map<id,decimal> mGrandParentAmt = new map<id,decimal>();
for(Account a :parents2) {
decimal grandParentAmt = 0.00;
if(mGrandParent.containsKey(a.parentId) {
grandParentAmt = mGrandParent.get(a.parentId);
}
if(mParentAmounts.containsKey(a.id)) {
grandParentAmt = grandParentAmt + mParentAmounts.get(a.id); // Can't use the amt from the SOQL, as we just created a new amount for the parents
} else {
grandParentAmt = grandParentAmt + a.Amt__c;
}
mGrandParentAmt.put(a.parentId,grandParentAmt);
}
// At this point we have two maps....
// mParentAmounts and mGrandparentAmts
// Now, get those account records and update the amount
list<account> accountsToUpdate = new list<Account>([SELECT id,Amt__c FROM Account WHERE id IN :mParentsAmounts.keyset() OR id IN :mGrandparentsAmts.keyset()]);
for(Account a :accountsToUpdate) {
if(mParentsAmounts.containsKey(a.id)) {
a.Amt__c = mParentsAmounts.get(a.id);
}
if(mGrandparentsAmt.containsKey(a.id)) {
a.Amt__c = mGrandparentsAmt.get(a.id);
}
}
Update accountsToUpdate;
}
Hope this helps.
Kindly mark this as solved if the reply was helpful.
I have used the above code however it is only calculating sumof childs and updating it on the Parent is there way to calculate sumof parents and showit on the grand parent or ultimate parent.
Please find the sample code below and tweak it as per the requirement. Hope this helps.
Kindly mark this as solved if the reply was helpful.
Thanks,
Nagendra
I have used the above code however it is only calculating sumof childs and updating it on the Parent is there way to calculate sumof parents and showit on the grand parent or ultimate parent.
Thanks
Kiran