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 if empty statement 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) {
campaignIds.add(cm.campaignId);
leadIds.add(cm.LeadId);
}
}
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
AND Systems_Group__c = NULL
AND Systems_Group__c = NULL]);
List<Lead> leadToUpdate = new List<Lead>();
for (CampaignMember cm : Trigger.new) {
if (cm.LeadId != NULL && cm.ContactId == NULL) {
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) {
thisLead.Systems_Group__c = thisCampaign.Systems_Group__c;
thisLead.System_Type__c = thisCampaign.System_Type__c;
if(!leadToUpdate.isEmpty()) {
leadToUpdate.add(thisLead);
}
}
}
}
if(!leadToUpdate.isEmpty()) {
update leadToUpdate;
}
}