I want to update the email optout field from converted contact to the existing contacts. For ex lets say i have 3 contacts with same email address([email protected]) and emailoptout not checked and iam converting new lead with emailoptout box checked and has same email([email protected]), i want my trigger to update the email optout box to true on these 3 existing contacts.
trigger updateLeadOnEmailOptOut on Lead (after update) {
List<Lead> duplicateLeads = new List<Lead>();
Map<String, Lead> leadEmailMap = new Map<String, Lead>();
Map<Id, Lead> leadIdMap = new Map<Id, Lead>();
Map<Id, Contact> contacts = new Map<Id, Contact>();
for (Integer i = 0; i < Trigger.new.size(); i++) {
if (Trigger.old[i].HasOptedOutOfEmail != Trigger.new[i].HasOptedOutOfEmail) {
leadEmailMap.put(Trigger.old[i].email, Trigger.new[i]);
leadIdMap.put(Trigger.old[i].id, Trigger.new[i]);
}
}
if ( leadIdMap.size() > 0 ) {
for ( Lead dupLead : [SELECT Id, Name, Email, HasOptedOutOfEmail FROM Lead
WHERE Email IN : leadEmailMap.KeySet()
AND Id NOT IN : leadIdMap.KeySet()
AND IsConverted = FALSE]) {
Lead lead = leadEmailMap.get(dupLead.Email);
if (dupLead.HasOptedOutOfEmail <> lead.HasOptedOutOfEmail) {
dupLead.HasOptedOutOfEmail = lead.HasOptedOutOfEmail;
duplicateLeads.add(dupLead);
}
}
if ( duplicateLeads.size() > 0 )
update duplicateLeads;
}
for ( Lead record : Trigger.new ) {
if ( record.ConvertedContactId != null ) {
contacts.put(record.ConvertedContactId, new Contact(Id=record.ConvertedContactId, HasOptedOutOfEmail=record.HasOptedOutOfEmail));
}
}
update contacts.values();
}