+ Start a Discussion
KevSnellKevSnell 

Trigger - Campaign Update All Campaign Members Field

Hi All,


I'm trying to find a solution for the following:

 

When the Campaign is set to Active it updates a custom field (CampaignField__c) in all Campaign Members for that Campaign.

 

I can't seem to find any examples when it comes to triggers with Campaigns.

 

I think the logic is:

  1. After Update
  2. Query CampaignMembers
  3. If Campaign ISActive = True
  4. Then CampaignField__c on CampaignMembers = True

Thanks

Kev 

KevSnellKevSnell

Ok I have my code to this point:

 

trigger CampaignMemberStatus on Campaign (after update) {
Set<ID> CampaignIds = new Set<ID>();


for(Campaign cam: Trigger.new)
    CampaignIDs.add(cam.id);
        List<CampaignMember> MemberToUpdate = new List<CampaignMember>([SELECT ID, Campaignid FROM CampaignMember WHERE CampaignMember.Campaignid = : CampaignIDs]);
        for(CampaignMember CamMem: MemberToUpdate) { 
        CamMem.Campaign_Active_V2__c = 'true';
        }
update MemberToUpdate;
}

 

However, I'm stuck on how do I add the statement IF > Campaign.Active = True

 

Salesforce DeveloperSalesforce Developer
Try as below: 
 
​trigger CampaignMemberStatus on Campaign (after update) {
    Set<ID> CampaignIds = new Set<ID>();

    for(Campaign cam: Trigger.new){
        if(cam.isActive){
            CampaignIds.add(cam.Id);
        }
    }
    List<CampaignMember> MemberToUpdate = new List<CampaignMember>();      
    for(CampaignMember CamMem: [SELECT ID, Campaignid, Campaign_Active_V2__c FROM CampaignMember WHERE CampaignMember.Campaignid IN: CampaignIds]) { 
          CamMem.Campaign_Active_V2__c = 'true';
          MemberToUpdate.add(CamMem);
    }
    if(!MemberToUpdate.IsEmpty())
        update MemberToUpdate;
}