function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Robert Wambold 10Robert Wambold 10 

compare lead email to contact email and update custom lead field when duplicate found

Hi All,

I am trying to update a custom field (NetNewLead__c) when a Lead's Email doesn't exist in Contact Email.

I am thinking a Trigger is the best solution, but my Apex skills are lacking.

I do not want to prevent creation of the Lead.

Can someone take a look at my code and offer advice?

Kind regards,

Robert

Code is below

trigger NetNewLead_Trigger on Lead (after update) {
    class UniqueKey {
        UniqueKey(String email) {
        this.email = email;
        }
        string Email;
        integer hashCode() {
            return toString().hashCode();
        }
        boolean equals(Object o) {
            return toString() == ((UniqueKey)o).toString();
        }
        public override string toString() {
            return String.format(
                'Email = \'\'{0}\'\'',
                new String[] {
                Email==null?'':String.escapeSingleQuotes(Email.tolowercase())
                }
            );
        }
    }

    Map<UniqueKey, Lead> leads = new Map<UniqueKey, Lead>();
    for(Lead record:Trigger.new) {
        if(record.isconverted) {
            UniqueKey key = new UniqueKey(record.email);
            if(leads.containskey(key)) {
                record.addError('Duplicate lead conversion.');
            } else {
                leads.put(key, record);
            }
        }
    }
    String[] keys = new String[0];
    for(UniqueKey key:leads.keyset()) {
        keys.add(key.tostring());
    }
    String query = string.format(
        'SELECT Id,Email,RecordTypeId FROM Contact WHERE RecordTypeId =:Client Contact" and {0}',
        new String[] {
            String.join(keys, ' OR ')
        }
    );
    if(!leads.isempty()) {
        for(Contact record:Database.query(query)) {
            UniqueKey key = new UniqueKey(record.email);
            if(leads.containskey(key)) {
                leads.get(key).addError('Duplicate lead conversion.');
            }
        }
    }

}

Best Answer chosen by Robert Wambold 10
Ravi Dutt SharmaRavi Dutt Sharma
Hi Robert,

Please use below code, this should fulfill your use case. I have put it comments so that the code becomes self explanatory. Note that I have only handled the insertion of leads, you can modify it if you want to handle update scenarios also.
 
trigger LeadTrigger on Lead (before insert) {
	
    if(Trigger.IsBefore && Trigger.isInsert){
        LeadTriggerHandler.checkNetNewLead(Trigger.new);
    }
}
 
public class LeadTriggerHandler {

    public static void checkNetNewLead(List<Lead> newLeads){
        Set<String> leadEmails = new Set<String>();
        // Step1: iterate over incoming leads and store email in a set
        for(Lead ld: newLeads){
            if(!String.isBlank(ld.Email)){
                leadEmails.add(ld.Email);
            }
        }
        // check whether there are any existing contacts in DB with matching email
        Map<Id,Contact> matchingContacts = new Map<Id,Contact>([SELECT Email FROM Contact WHERE Email IN:leadEmails]);
        // iterate over the map values and store the email in set
        Set<String> contactEmails = new Set<String>();
        for(Contact con: matchingContacts.values()){
            contactEmails.add(con.Email);
        }
        // Step2: Again iterate over incoming leads and check if contact with matching email exists
        for(Lead ld: newLeads){
            // if match is found, then update NetNewLead__c as false
            if(contactEmails.contains(ld.Email)){
                ld.NetNewLead__c = false;
            }
        }
    }
}

 

All Answers

Ravi Dutt SharmaRavi Dutt Sharma
Can you please provide more details for your requirement. What I understood is that there is a boolean field on lead called NetNewLead__c. On lead creation, NetNewLead__c should be checked to true if lead email does not match with any of the existing contacts email.
Robert Wambold 10Robert Wambold 10

Ravi,

Thanks for your reply.

I created Lead.NetNewLead__c with a default value of True. If the Contact.Email from Lead.Email already exists I want to change Lead.NetNewLead__c to False.

I applogize in advance for my code.

Kind regards,

Robert

Ravi Dutt SharmaRavi Dutt Sharma
Hi Robert,

Please use below code, this should fulfill your use case. I have put it comments so that the code becomes self explanatory. Note that I have only handled the insertion of leads, you can modify it if you want to handle update scenarios also.
 
trigger LeadTrigger on Lead (before insert) {
	
    if(Trigger.IsBefore && Trigger.isInsert){
        LeadTriggerHandler.checkNetNewLead(Trigger.new);
    }
}
 
public class LeadTriggerHandler {

    public static void checkNetNewLead(List<Lead> newLeads){
        Set<String> leadEmails = new Set<String>();
        // Step1: iterate over incoming leads and store email in a set
        for(Lead ld: newLeads){
            if(!String.isBlank(ld.Email)){
                leadEmails.add(ld.Email);
            }
        }
        // check whether there are any existing contacts in DB with matching email
        Map<Id,Contact> matchingContacts = new Map<Id,Contact>([SELECT Email FROM Contact WHERE Email IN:leadEmails]);
        // iterate over the map values and store the email in set
        Set<String> contactEmails = new Set<String>();
        for(Contact con: matchingContacts.values()){
            contactEmails.add(con.Email);
        }
        // Step2: Again iterate over incoming leads and check if contact with matching email exists
        for(Lead ld: newLeads){
            // if match is found, then update NetNewLead__c as false
            if(contactEmails.contains(ld.Email)){
                ld.NetNewLead__c = false;
            }
        }
    }
}

 
This was selected as the best answer
Robert Wambold 10Robert Wambold 10

Thank you so much!

When I try to save I am getting errors.

User-added image

 

Robert Wambold 10Robert Wambold 10

I should not have saved LeadTrigger before LeadTriggerHandler...that is the first error (line 4).

Not sure what is causing LeadTriggerError "invalid parameter value"
 

Ravi Dutt SharmaRavi Dutt Sharma
Not sure, maybe some extra characters while copying from here and pasting the code in developer console. Can you copy the code from here, paste it in Notepad, then copy it back and paste it in the class in your developer console.
Robert Wambold 10Robert Wambold 10
Ravi thank you so much! I am up to 83% on my first test class...going for 100%.
Ravi Dutt SharmaRavi Dutt Sharma
Great, keep going.