I have a trigger on contacts that is causing DML errors and I'm not sure where the problem is as I only have one update on a list.
This is occurring when I am using the Data loader to update about 30k contacts.
public class ContactTriggerHandler extends TriggerHandler{
protected override void beforeUpdate() {
Map<Id, Contact> newMarketingQualifiedLeads = new Map<Id, Contact>();
for(Contact tempContact : (list<Contact>)trigger.new){
Contact oldContact = (Contact)trigger.oldMap.get(tempContact.Id);
//Check that the contact is an MQL and that the value was newly checked.
boolean tempContactMQL = tempContact.PB_Marketing_Qualified_Lead__c;
if((tempContactMQL == true) && (tempContactMQL != oldContact.PB_Marketing_Qualified_Lead__c)){
newMarketingQualifiedLeads.put(tempContact.Id, tempContact);
}
}
//check the campaign produced MQL for all new MQLS
if(checkRecursive.runContactTrigger1 && !newMarketingQualifiedLeads.isEmpty()){
checkRecursive.runContactTrigger1 = false;
checkCampaignProducedMQL(newMarketingQualifiedLeads);
}
} // end beforeUpdate()
/* **********************
* When the “Marketing Qualified Lead” checkbox is populated on a Lead or Contact,
* find the most recent campaign the Lead/Contact was associated to and
* check the “Campaign Produced MQL” checkbox (which is on the Campaign Member object).
* **********************/
private void checkCampaignProducedMQL(Map<Id, Contact> newMarketingQualifiedLeads){
// Query to determine the contacts who have already been assigned a Campaign Produced MQL
List<Contact> contactsWhoAlreadyHaveSetCPMQL = [SELECT Id FROM Contact WHERE Id IN (SELECT ContactID FROM CampaignMember
WHERE ContactID IN :newMarketingQualifiedLeads.keySet()
AND Campaign_Produced_MQL__c = TRUE)
];
// Remove the contacts who have already been assigned a Campaign Produced MQL from the list
for(Contact tempContact : contactsWhoAlreadyHaveSetCPMQL){
newMarketingQualifiedLeads.remove(tempContact.Id);
}
// Query for the most recent Campaign assigned to each contact
List<Contact> contactsWithNewestCampaignMember = [SELECT Id, Name, (SELECT ID, CreatedDate From CampaignMembers ORDER BY CreatedDate DESC LIMIT 1)
FROM Contact WHERE Id IN :newMarketingQualifiedLeads.keySet()];
// Mark each campaignMember as the Campaign Produced MQL
CampaignMember campaignMember;
List<CampaignMember> cmList = new List<CampaignMember>();
for(Contact tempContact : contactsWithNewestCampaignMember){
try{
campaignMember = tempContact.CampaignMembers;
campaignMember.Campaign_Produced_MQL__c = true;
cmList.add(campaignMember);
}
catch (exception e){
system.debug('Unable to set a Campaign Produced MQL for user ID: ' + tempContact.Id);
}
}
update cmList;
}
}