Goal: 'Bulkify' the existing Apex trigger used for counting how many dupes a Lead had, and inserting the Contact Id of the Contact record (if more than one, the first in the list) that matched the email address of the Lead.
Here's a snippet of the code I want to bulkify:
for (Lead l : Trigger.new) {
//Make sure our lead has an email address
if (l.Email != null) {
//Find a dupe
String leadEmail = l.Email;
List<Lead> dupeLeads = [SELECT Id FROM Lead WHERE Email = :leadEmail];
//If a dupe is found, update a field
if (dupeLeads.size() > 0) {
l.Dupe_Lead_Counter__c = dupeLeads.size();
} else {
//0 would designate a true unique
l.Dupe_Lead_Counter__c = 0;
}
So, this is clearly violating the mandate of 'No SOQL queries in For() loops.'
Reading the various doucmentation and tutorials, it looks as though the pattern needs to be a List of the sObjects we want to query from (all Leads with email values in this case) and then use mapping to somehow map the lists of dupe Leads (by email) with the master Lead email list.
How do I even group duplicate emails into a List without creating a For() loop/SOQL query in the first place?
This is what I have so far:
Set<String> leadsWithEmails = new Set<String>();
for (Lead l : Trigger.new) {
if(l.email != null) {
leadsWithEmails.add(l.Email);
}
}
//Query for all Leads
List<Lead> potentialDupeLeads = [SELECT Id,Email FROM Lead
WHERE Email IN :leadsWithEmails];
//Step 3: Make a map that lets you search for Leads by Email
Map<String, Lead> emailToLeadMap = new Map<String, Lead>();
for (Lead l : potentialDupeLeads) {
emailToLeadMap.put(l.Email, l);
}
z
innew Set<z String>();
z
intentional?Invalid foreign key relationship
this statement is tripping it up:record.Lead.Dupe_Lead_Counter__c = count;