+ 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)
  // 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)
  // Do not create a record for null field
  // 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'])
  // Update all the contacts with new values.

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


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