+ Start a Discussion
GtennentGtennent 

Rollup Summary trigger on lookup relationship.

I'm using the Nonprofit Starter Pack and I would like a way for volunteer hours to displace on household(account) pages as well as the contact page. I have already added an account lookup field, because I can't use Master-Detail. I think those have already been used for the contact and the volunteer job. So now I'm trying to create a trigger that updates the Total Hours field on the account, which is a sum of the hours field on the volunteer hour object. My question is how do I write code to sum those hours for the correct? Here's where I am thus far.
trigger RollupVolunteerHours on Volunteer_Hours__c (After insert, after update, after delete) {
	Set<Id> AccountIds = new Set<Id>();
    list<Volunteer_Hours__c> vHours = [SELECT Id, Hours__c FROM Volunteer_Hours__c WHERE Id IN :trigger.new];
    for(Volunteer_Hours__c vh :trigger.new){
        AccountIds.add(vh.Account__r.Id);
    }
	
    list<Account> acctList = [SELECT Id, Total_Hours__c FROM Account WHERE Id IN :AccountIDs];
    
    For(Account acct : acctList){
        //acct.Total_Hours__c = Summation of Volunteer_Hours__r.Hours__c
        
        update acct;
    }
}

Am I on the right track? How do I use what I have to do what I want? If something is unnecessary, why? Same for missing. I'm fairly new to apex so please explain steps instead of giving me code. I want to learn and understand!

Thanks!

Hargobind_SinghHargobind_Singh
Hi Geoff, 

You are on the right track. Here are my suggestions: 
  • After you have collected all Account IDs in AccountIDs list, run an aggregate query on Volunteer_Hours object (between line 6 and 8) to get the sum of hours for those Accounts. 
  • Store the sum in a map, so that you don't have to run the loop inside a loop on row 11
  • On row 11, update that sum
Here is some info on aggregate functions: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm

And some help on maps:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bulk_idioms.htm

ps: I wrote a reply earlier and deleted as I read your code again :) 
Anupam Bansal (Capgemini)Anupam Bansal (Capgemini)

Hi Geoff,

Although you can write your own code to develop this functionality, but there is already something generic written on this topic. So if you want to use a generic solution and have time to explore you can have a  look at this

https://developer.salesforce.com/page/Declarative_Rollup_Summary_Tool_for_Force.com_Lookup_Relationships

Thanks,
Anupam Bansal
OSI Consulting