0

I have multiple Web-to-Lead forms that gather information for different fields. I want to store all the info under one lead, with the email address being the key. I want to create a trigger to query Leads to see if the email exists. If it does, I want to add this information on to the existing Lead. I am able to find if there is a duplicate email address, but I don't know how to merge the two together.

trigger leadDupeMerge on Lead (before insert) {
Set<String> emails = new Set<String>();
for(Lead ld : trigger.new){
    emails.add(ld.Email);
}
emails.remove(null);
for(Lead ld: [SELECT Email FROM Lead WHERE Email = :emails]){
    emails.remove(ld.Email);
}
for(Lead ld : Trigger.new){
    if(ld.Email != null && emails.contains(ld.Email)){
        ld.Email.addError('This lead matches an existing email.');
    }
}

}

1 Answer 1

0

You'll need to use after insert instead if you want to perform an actual merge operation. That logic would look like:

trigger leadDupeMerge on Lead (after insert) {
    Set<String> emails = new Set<String>();
    Map<String, Lead> masters = new Map<String, Lead>();
    for(Lead ld : trigger.new){
        emails.add(ld.Email);
    }
    emails.remove(null);
    for(Lead ld: [SELECT Email FROM Lead WHERE Email = :emails AND Id NOT IN :Trigger.new AND IsConverted = false]){
        masters.put(ld.Email, ld);
    }
    for(Lead ld : Trigger.new){
        Lead master = masters.get(ld.Email);
        if(master != null) {
            merge master ld;
        }
    }
}

Notes:

  • No error handling is provided here. If you run into errors, you'll need to handle those.
  • If a user performs a create through the UI and it is a duplicate, they'll see a "record deleted" page instead of the lead they just created.
  • Merges can't be bulkified, so you may want to return early if the list size is greater than 1 (web-to-lead and the like usually insert one record at a time).
4
  • In line 6, you have record.Email. I'm not sure where the variable record is coming from. Can you explain this for me? Feb 10, 2020 at 15:12
  • @LukeHiggins that was a copy-paste error. I've edited the answer.
    – sfdcfox
    Feb 10, 2020 at 15:36
  • The trigger prevents duplicate entries, but it doesn't allow for any data to be added to the already existing Lead record. I would like for it to overwrite the existing data as well as keep the data that have empty fields on the new entry. Feb 10, 2020 at 19:22
  • @LukeHiggins You can implement that with more logic (query all fields you're interested in, copy fields selectively, etc). The merge function really only handles merging related records, campaign data, etc.
    – sfdcfox
    Feb 10, 2020 at 19:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .