+ Start a Discussion
msreekmmsreekm 

Prevent duplicate Lead Trigger

How do we check duplicates for multiple fields in leads. (email address ,company and phone)

 

leadDuplicatePreventer trigger (below) in the cookbook has the code for checking duplicate in email address. but what is the best way to  add more fields..

 

trigger leadDuplicatePreventer on Lead (before insert, before update) {

Map<String, Lead> leadMap = new Map<String, Lead>();

for (Lead lead : System.Trigger.new) {

if ((lead.Email != null) &&

    (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) {

if (leadMap.containsKey(lead.Email)) {

  lead.Email.addError('Another new lead has the ' + 'same email address.');

} else { 

    leadMap.put(lead.Email, lead); 

}

}

}

for (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) {

Lead newLead = leadMap.get(lead.Email);

newLead.Email.addError('A lead with this email ' + 'address already exists.');

}

}

HarmpieHarmpie

Easiest way without having to rebuild/restructure this trigger is probably to create a custom lead field of type formula. Add fields email, company and phone as 1 string in this field.

 

Then modify the trigger, replace all occurences of email to your_custom_formula_field__c.

ycaballeroycaballero

The lead custom does not let me add email to the formula.  Is there any other way to add more than field to the trigger?

msreekmmsreekm

ycaballero- if formula field is not letting you add email fields, you could do that in a trigger.

ycaballeroycaballero

I am also using the trigger from the cookbook.

 

What i am looking to do is for the trigger to look at two fields.  Email & Record type.  I want it to update the record if it finds a duplicate.  How do write that in the following trigger?

 

I would really appreciate the help.

 

 

trigger leadDuplicatePreventer on Lead (before insert, before update) {

Map<String, Lead> leadMap = new Map<String, Lead>();

for (Lead lead : System.Trigger.new) {

if ((lead.Email != null) &&

    (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) {

if (leadMap.containsKey(lead.Email)) {

  lead.Email.addError('Another new lead has the ' + 'same email address.');

} else { 

    leadMap.put(lead.Email, lead); 

}

}

}

for (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) {

Lead newLead = leadMap.get(lead.Email);

newLead.Email.addError('A lead with this email ' + 'address already exists.');

}

}

 

 

Nagarjuna Reddy NandireddyNagarjuna Reddy Nandireddy
I think this is simple answer for it.................


trigger leadDuplicatePreventer on Lead (before insert,after update) {
  list<lead> lead = new   list<lead>(); 
 for(lead a: trigger.new)
 {
lead=[select id,name,email from lead where email=:a.email];
  if(lead.size()>0)
  {
   a.email.adderror('email already exist');
  }
 }
}