Print this page

Apex Trigger cross-object field update

Knowledge Article Number 000002636
Description

In order to update a field on object B based on criteria of object A you have to use apex. We'll give you some example code to help you get started. 

 

Resolution

Example: Update Contact based on update/insert of CampaignMember

Trigger UpdateField on CampaignMember (after update, after insert)

{
List<Contact> contactsToUpdate = new List<Contact>();

   // For each CampaignMember, update contact
    for (CampaignMember o : Trigger.new){
        Contact tempContact = new Contact(Id = o.contactid);
   // Only update contacts that we need to update
        If(tempContact.Do_not_email__c != o.Do_not_email__c){
           tempContact.Do_not_email__c = o.Do_not_email__c;
           contactsToUpdate.add(tempContact);

        }

    }
    // update Contacts
    update contactsToUpdate;

}




promote demote