Hoping you can help..
We receive bulk email marketing data into Salesforce which creates 'events'. These events include things like the date, if any URL was clicked and if so, what the URL was. We are trying to track these URLs and increase a custom field on a lead by 1 for every click. I have coded this part and it is working fine.
The issue I'm having is with bulkifying the dml update procedure to stay below governor limits. The modified leads are added to a list and then a dml update is run. If someone clicks on two different email links then they will appear in the bulk data twice and subsequently in the update list twice which throws an error as you are not allowed duplicates in a list to be updated.
I'm new to apex so I'm hoping there's something I'm missing or haven't thought of. Thanks in advance for your help. My code so far (simplified for this post):
trigger UpdateSoftOptIns on amf__MFLaunchEvent__c (before insert) {
Set<String> allLeads = new Set<String>();
for (amf__MFLaunchEvent__c eventInLoop : Trigger.new) {
if (eventInLoop.Name == 'click' && eventInLoop.amf__lead__c != null) {
allLeads.add(eventInLoop.amf__lead__c);
}
}
List<Lead> listOfLeads = [SELECT Id,
CustomerOptIn01__c,
CustomerOptIn02__c
FROM Lead
WHERE Id IN :allLeads];
Map<String, Lead> idToLeadMap = new Map<String, Lead>();
for (Lead l : listOfLeads) {
idToLeadMap.put(l.Id, l);
}
List<Lead> leadUpdateList = new List<Lead>();
for (amf__MFLaunchEvent__c eventInLoop : Trigger.new) {
if (eventInLoop.Name == 'click' && eventInLoop.amf__lead__c != null) {
Lead leadToUpdate = idToLeadMap.get(eventInLoop.amf__lead__c);
if (eventInLoop.amf__link__c == 'https://www.acme.com/catalogue?=&course[]=60') {
if (leadToUpdate.CustomerOptIn01__c == null) {
leadToUpdate.CustomerOptIn01__c = '1';
} else if (leadToUpdate.CustomerOptIn01__c == '10') {
leadToUpdate.CustomerOptIn01__c = '10';
} else {
Integer i = Integer.valueOf(leadToUpdate.CustomerOptIn01__c) + 1;
leadToUpdate.CustomerOptIn01__c = String.valueOf(i);
}
} else if (eventInLoop.amf__link__c == 'https://www.acme.com/catalogue?=&course[]=58') {
if (leadToUpdate.CustomerOptIn02__c == null) {
leadToUpdate.CustomerOptIn02__c = '1';
} else if (leadToUpdate.CustomerOptIn02__c == '10') {
leadToUpdate.CustomerOptIn02__c = '10';
} else {
Integer i = Integer.valueOf(leadToUpdate.CustomerOptIn02__c) + 1;
leadToUpdate.CustomerOptIn02__c = String.valueOf(i);
}
leadUpdateList.add(leadToUpdate);
}
}
update leadUpdateList;
}