0

I wrote a trigger to update the lead associated to new campaign members with values from the associated campaign. The leads should only be updated from the campaign if the fields are blank on the lead.

What I am seeing is that the leads get updated from the campaign, but are getting updated even if they are already populated with a value on the lead.

Not sure why the criteria of null values is getting ignored.

trigger deleteThisTrigger on CampaignMember (before insert) {
    Set<Id> campaignIds = new Set<Id>();
    Set<Id> leadIds = new Set<Id>();

    for (CampaignMember cm : Trigger.new) {
        if (cm.LeadId != NULL && cm.ContactId == NULL && cm.Lead.System_Type__c == NULL && cm.Lead.Systems_Group__c == NULL) {
            campaignIds.add(cm.campaignId);
            leadIds.add(cm.LeadId);

          System.debug(campaignIds);
        }
    }

    Map<Id, Campaign> campaignMap = new Map<Id, Campaign> ([SELECT System_Type__c, Systems_Group__c
                                    FROM Campaign
                                    WHERE Id IN :campaignIds]);

    Map<Id, Lead> leadMap = new Map<Id, Lead> ([SELECT System_Type__c, Systems_Group__c
                                    FROM Lead
                                    WHERE Id IN :leadIds]);

        System.debug(campaignMap);

    List<Lead> leadToUpdate = new List<Lead>{};

    for (CampaignMember cm : Trigger.new) {
        if (cm.LeadId != NULL && cm.ContactId == NULL && cm.Lead.System_Type__c == NULL && cm.Lead.Systems_Group__c == NULL) {
            Campaign thisCampaign = campaignMap.get(cm.CampaignId);
            Lead thisLead = leadMap.get(cm.LeadId);

            System.debug(thisCampaign.Systems_Group__c);
            System.debug(cm.LeadId);

            thisLead.Systems_Group__c = thisCampaign.Systems_Group__c;
            thisLead.System_Type__c = thisCampaign.System_Type__c;

            leadToUpdate.add(thisLead);

        }
    }

    system.debug(leadToUpdate);

    update leadToUpdate;

}

1 Answer 1

2

Related object fields in Trigger.new are not populated, so they'll always appear as null. You need to get the lead you queried and check that record instead:

Campaign thisCampaign = campaignMap.get(cm.CampaignId);
Lead thisLead = leadMap.get(cm.LeadId);
if (thisLead != null && thisLead.System_Type__c == NULL && thisLead.Systems_Group__c == NULL) {

You must log in to answer this question.

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