I have a custom field called Total number of rooms on the Account Object.
Now, I have a custom lookup relationship from Account to Account called portfolio
A portfolio will have several accounts associated with it
On the Portfolio Account page, I want to show the sum of the total number of rooms for the related Accounts
Eg: If the portfolio has 2 Accounts, 1 account has 2 rooms and 2nd account has 3 rooms, then the portfolio should show 5 rooms in total.
It should also consider that , if one account is removed from the portfolio, the count should decrease
Below is the trigger that I have written to implement the below code
Sum of Total_Rooms__c works perfectly that is if related accounts are removed from the related list, the value of Total rooms get decreased and if related Accounts are added the value of rooms get incremented
If i remove the Portfolio association from the related account page, the value of Sum of rooms doesnt get updated.
What do I should in this case
trigger AccountRollup on Account (after delete, after insert, after update) {
//Limit the size of list by using Sets which do not contain duplicate elements
set<Id> AccountIds = new set<Id>();
//When adding new Portfolio or updating existing Portfolio
if(trigger.isInsert || trigger.isUpdate){
for(Account p : trigger.new){
AccountIds.add(p.Portfolio__c);
}
}
//When deleting Portfolio
if(trigger.isDelete){
for(Account p : trigger.old){
AccountIds.add(p.Portfolio__c);
}
}
//Map will contain one Portfolio Id to one sum value
map<Id,Double> AccountMap = new map <Id,Double>();
//Produce a sum of Total Rooms on Portfolios and add them to the map
//use group by to have a single Portfolio Id with a single sum value
for(AggregateResult q : [select Portfolio__c,sum(Total_Rooms__c)
from Account where Portfolio__c IN :AccountIds group by Portfolio__c]){
AccountMap.put((Id)q.get('Portfolio__c'),(Double)q.get('expr0'));
}
List<Account> AccountsToUpdate = new List<Account>();
//Run the for loop on Accounts using the non-duplicate set of Portfolio Ids
//Get the sum value from the map and create a list of Accounts to update
for(Account a : [Select Id, Total_Rooms__c from Account where Id IN :AccountIds]){
Double RoomSum = AccountMap.get(a.Id);
a.Total_Rooms__c = RoomSum;
AccountsToUpdate.add(a);
}
update AccountsToUpdate;
}