• Admin User 586
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
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

Hi,

 

I want to create a rollup field in Account Object with Opportunity Amount. Can any one help me on this, Actually i'm new in  trigger.