0

So I've been trying to use a trigger. But it's not working. Ive created thid method that gets called in afterInsert and afterUpdate. So I'm testing it by adding a lead on Campaign Member and nothing changes.What am i doing wrong?

private void setCampaignNameOnLead(List<Lead> newLeads) {

    System.debug('NEW LEADS ' + newLeads);

    Set<Id> leadIds = new Set<Id>();

    for (Lead l : newLeads) {

        leadIds.add(l.Id);

    }



    // Query for CampaignMember records to get the related Campaign Names

    Map<Id, String> leadIdToCampaignName = new Map<Id, String>();

    for (CampaignMember cm : [SELECT LeadId, Campaign.Name FROM CampaignMember WHERE LeadId IN :leadIds]) {

        leadIdToCampaignName.put(cm.LeadId, cm.Campaign.Name);

    }



    // Update leads with the corresponding Campaign names

    List<Lead> leadsToUpdate = new List<Lead>();

    for (Lead l : newLeads) {

        if (leadIdToCampaignName.containsKey(l.Id)) {

            l.Campaign_Name__c = leadIdToCampaignName.get(l.Id);

            leadsToUpdate.add(l);

        }

    }



    if(!leadsToUpdate.isEmpty()) {

        update leadsToUpdate;

    }



}

Edit: I have tried adding the trigger on CampaignMember this is what it looks like.

This is part of the class that dispatches triggers

  if (Trigger.IsBefore ){



        if (Trigger.IsInsert)

            handler.BeforeInsert(trigger.new);

    }

     

    if (Trigger.IsAfter) {

       

        if (Trigger.IsInsert)

            handler.AfterInsert(Trigger.newMap);

 }

This is part of the class that i made to trigger the CampaignMembers

public void BeforeInsert(List<SObject> newItems) {

    if (!IsDisabled()) {

        this.setCampaignNameOnLead((List<CampaignMember>) newItems);

    }

}

private void setCampaignNameOnLead(List newCampaignMember) {

    List<Lead> leads = new List<Lead>();

        for (CampaignMember cm : newCampaignMember) {

            if(cm.LeadId != Null){

                Lead lead = new Lead(Id=cm.LeadId,Campaign_Name__c = cm.Name);

                leads.add(lead);

            }

        }

    update leads;

}
3
  • 1
    Can you include code that shows how your trigger handler is called from the trigger?
    – nbrown
    Feb 9 at 16:09
  • what object is the trigger coded on? Needs to be CampaignMember, not Lead
    – cropredy
    Feb 9 at 22:47
  • Updated the code Feb 12 at 8:52

1 Answer 1

0

You are setting the Campaign_Name__c field to the Name of the CampaignMember record. You need to reference the Campaign parent by traversing the relationship:

Campaign_Name__c = cm.Campaign.Name 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .