function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Admin User 586Admin User 586 

Rollup summary campaign to contact

Hi there,

I am trying to create a trigger rollup summary from campaigns to contacts and would really appreciate some help. Contacts are associated with campaigns through a lookup field called Chosen_Tutor__c.

What I am trying to do is to create a rollup summary of a number field called Hours_per_week__c on the object campaigns into a number field on the related contact called Live_Hours_Rollup__c. The condition of the rollup should be that only campaigns with status "Live job" are summarised. I have pasted the code that I have tried to implement below which is not working:
 
trigger Livehoursrollup on campaign (after insert, after update, after delete, after undelete) {
  Map<Id,Contact> updateContacts = new Map<Id,Contact>();
  Set<Id> updateContactIds = new Map<Id,Contact>();
  // If we are inserting, updating, or undeleting, use the new ID values
  if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    for(campaign campaign:Trigger.new)
      updateContactIds.add(campaign.Chosen_Tutor__c);
  // If we are updating, some contacts might change, so include that as well as deletes
  if(Trigger.isUpdate || Trigger.isDelete)
    for(campaign campaign:Trigger.old)
      updateContactIds.add(campaign.Chosen_Tutor__c);
  // Do not create a record for null field
  updateContactIds.remove(null);
  // Create in-memory copies for all contacts that will be affected
  for(Id contactId:updateContactIds)
    updateContacts.put(contactId,new Contact(id=contactId,Live_Hours_Rollup__c=0));
  // Run an optimized query that looks for all contacts that meet the if/then criteria
  for(campaign campaign:[select id,Hours_per_week__c from campaign where Chosen_Tutor__c in :updateContactIds and Status__c='Live job'])
    updateContacts.get(campaign.Chosen_Tutor__c).Live_Hours_Rollup__c++;
  // Update all the contacts with new values.
  Database.update(updateContacts.values());
}

Any help would be much appreciated. I am an apex newbie!

Thanks,

L
UC InnovationUC Innovation
Do you need to use a trigger for this?  You can do this with flows:

http://www.salesforceweek.ly/2015/02/how-to-create-roll-up-summaries-using-flow.html