I want to track our email lists dynamically using a single-choice picklist for each email list with options of 'Subscribed' and 'Unsubscribed' that automatically assigns subscribers to a Campaign. I created a trigger that works beautifully when the specific field is named -- but I don't want to create a separate trigger for each field. Instead I want to create a for loop that iterates over the Map that holds all the relevant fields as keys and looks up CampaignId values to assign subscribers to.
The code below works on the isInsert, but fails to create a CampaignMember record in the isUpdate. The isUpdate section is necessary to avoid a duplicate error if I batch upload records, some of which already have CampaignMember records. How can I get the for loop to evaluate the Boolean expression properly? All I need is to avoid the DUPLICATE_ERROR by comparing most recent field history and check against post-update field history to make sure they weren't both 'Subscribed.'
trigger EmailSubscribe on Contact (after insert, after update) {
Map<String,String> varNameToValueMap = new Map<String,String>();
varNameToValueMap.put('Email_List1__c','70117000000vgRA');
varNameToValueMap.put('Email_List2__c','70117000000vgRF');
list<contact> triggerNew = Trigger.new;
for(String sub : varNameToValueMap.keySet()){
List <Contact> ContactList = (List<Contact>) Database.query('Select Id FROM Contact WHERE ' + sub + ' = \'Subscribed\' AND Id in :triggerNew');
List <CampaignMember> NewMembers = new List<CampaignMember>();
if(ContactList.size() > 0){
if(Trigger.isInsert){
//iterate over inserted contacts and enter into previously empty list
for (Contact l:ContactList){
newMembers.add(new CampaignMember(
ContactId = l.Id,
CampaignId = varNametoValueMap.get(sub),
Status = 'Subscribed'));
}
}
else {
for(Contact c : Trigger.new) {
Contact con = Trigger.oldMap.get(c.Id);
String oldCon = 'con.' + sub + '.equals(\'Subscribed\');';
String newCon = 'c.' + sub + '.equals(\'Subscribed\');';
Boolean oldConSub = Boolean.valueOf(oldCon);
Boolean newConSub = Boolean.valueOf(newCon);
//only add updated records to list for upload if subscription field was changed from non-subscriber to subscriber
if(!oldConSub && newConSub) {
newMembers.add(new CampaignMember(
ContactId = c.Id,
CampaignId = varNametoValueMap.get(sub),
Status = 'Subscribed'));
}
}
}
//upload list of subscribers to group
insert NewMembers;
}
}
}