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
Aaron HillAaron Hill 

Updating lead dupe catching recipe

Hey everyone,

I'm using a recipie from the Force.com cookbook to prevent duplicate records from saving. Here's the link: http://developer.force.com/cookbook/recipe/preventing-duplicate-records-from-saving
 
trigger leadDuplicatePreventer on Lead
                               (before insert, before update) {

    Map<String, Lead> leadMap = new Map<String, Lead>();
    for (Lead lead : System.Trigger.new) {
		
        // Make sure we don't treat an email address that  
        // isn't changing during an update as a duplicate.  
    
        if ((lead.Email != null) &&
                (System.Trigger.isInsert ||
                (lead.Email != 
                    System.Trigger.oldMap.get(lead.Id).Email))) {
		
            // Make sure another new lead isn't also a duplicate  
    
            if (leadMap.containsKey(lead.Email)) {
                lead.Email.addError('Another new lead has the '
                                    + 'same email address.');
            } else {
                leadMap.put(lead.Email, lead);
            }
       }
    }
	
    // Using a single database query, find all the leads in  
    
    // the database that have the same email address as any  
    
    // of the leads being inserted or updated.  
    
    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.');
    }
}

My question, how do I modify this code in another trigger so that it prevents lead/contact duplicates  from being synched? Again this trigger should still be for leads being inserted but I want it to match against existing contact email rather than existing lead email. Thanks!
Best Answer chosen by Aaron Hill
Deepak GulianDeepak Gulian
Trigger:-
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){
                leadMap.put(lead.Email, lead);
        }
    }
    
    for (Contact con : [SELECT Email FROM Contact WHERE Email IN :leadMap.KeySet()]) {
        Lead newLead = leadMap.get(con.Email);
        newLead.Email.addError('A Contact with this email '
                               + 'address already exists.');
    }
}

Test Class:-
@isTest
public class leadDupePreventerTests{
    static testMethod void testLeadDupPreventer() {
        
      
      // Account
         Account acc = new Account(
            Name = 'Test Account1'
         );
        insert acc;
      
      // Contacts
      Contact con1 = new Contact( FirstName = 'Fbname', LastName = 'LbName', Email = 'test1@duptest.com', AccountId = acc.Id );
      Contact con2 = new Contact( FirstName = 'Fbname', LastName = 'LbName', Email = 'test7@duptest.com', AccountId = acc.Id );
      Contact[] cons = new Contact[] {con1, con2};
      insert cons;

      // First make sure there are no leads already in the system
      // that have the email addresses used for testing
      Set<String> testEmailAddress = new Set<String>();
      testEmailAddress.add('test1@duptest.com');
      testEmailAddress.add('test2@duptest.com');
      testEmailAddress.add('test3@duptest.com');
      testEmailAddress.add('test4@duptest.com');
      testEmailAddress.add('test5@duptest.com');
      System.assert([SELECT count() FROM Lead
                     WHERE Email IN :testEmailAddress] == 0);
        
      // Seed the database with some leads, and make sure they can
      // be bulk inserted successfully.
      Lead lead2 = new Lead(LastName='Test2', Company='Test2 Inc.',
                            Email='test4@duptest.com');
      Lead lead3 = new Lead(LastName='Test3', Company='Test3 Inc.',
                            Email='test5@duptest.com');
      Lead[] leads = new Lead[] {lead2, lead3};
      insert leads;        
                                          
      // Make sure that single row lead duplication prevention works
      // on insert.
      Lead dup1 = new Lead(LastName='Test1Dup',
                           Company='Test1Dup Inc.',
                           Email='test1@duptest.com');
      try {
         insert dup1;
         System.assert(false);
      } catch (DmlException e) {
         System.debug(e.getDmlMessage(0));
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 0);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf('A Contact with this email address already exists.') > -1);
      }
        
      // Make sure that single row lead duplication prevention works
      // on update.
      lead2 = new Lead(Id = lead2.Id, LastName='Test1Dup',
                      Company='Test1Dup Inc.',
                      Email='test7@duptest.com');
      try {
         update lead2 ;
         System.assert(false);
      } catch (DmlException e) {
         System.debug(e.getDmlMessage(0));
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 0);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf('A Contact with this email address already exists.') > -1);
        }
    
      
   }
}
Update old Trigger with above Trigger!

All Answers

Deepak GulianDeepak Gulian
trigger leadDuplicatePreventer on Lead
                               (before insert, before update) {

    Map<String, Lead> leadMap = new Map<String, Lead>();
    for (Lead lead : System.Trigger.new) {
		
        // Make sure we don't treat an email address that  
        // isn't changing during an update as a duplicate.  
    
        if ((lead.Email != null) &&
                (System.Trigger.isInsert ||
                (lead.Email != 
                    System.Trigger.oldMap.get(lead.Id).Email))) {
		
            // Make sure another new lead isn't also a duplicate  
    
            if (leadMap.containsKey(lead.Email)) {
                lead.Email.addError('Another new lead has the '
                                    + 'same email address.');
            } else {
                leadMap.put(lead.Email, lead);
            }
       }
    }
	
    // Using a single database query, find all the leads in  
    
    // the database that have the same email address as any  
    
    // of the leads being inserted or updated.  
    
    for (Contact con : [SELECT Email FROM Contact
                      WHERE Email IN :leadMap.KeySet()]) {
        Lead newLead = leadMap.get(con.Email);
        newLead.Email.addError('A Contact with this email '
                               + 'address already exists.');
    }
}
Try this!
 
Aaron HillAaron Hill
Deepak,


Works great in sandbox! I appreciate your help, if you don't mind, can you give me some pointers on fixing the test class too? Here is what I had for the other rule.

 
@isTest
public class leadDupePreventerTests{
    static testMethod void testLeadDupPreventer() {
        
      // First make sure there are no leads already in the system
      // that have the email addresses used for testing
      Set<String> testEmailAddress = new Set<String>();
      testEmailAddress.add('test1@duptest.com');
      testEmailAddress.add('test2@duptest.com');
      testEmailAddress.add('test3@duptest.com');
      testEmailAddress.add('test4@duptest.com');
      testEmailAddress.add('test5@duptest.com');
      System.assert([SELECT count() FROM Lead
                     WHERE Email IN :testEmailAddress] == 0);
        
      // Seed the database with some leads, and make sure they can
      // be bulk inserted successfully.
      Lead lead1 = new Lead(LastName='Test1', Company='Test1 Inc.',
                            Email='test1@duptest.com');
      Lead lead2 = new Lead(LastName='Test2', Company='Test2 Inc.',
                            Email='test4@duptest.com');
      Lead lead3 = new Lead(LastName='Test3', Company='Test3 Inc.',
                            Email='test5@duptest.com');
      Lead[] leads = new Lead[] {lead1, lead2, lead3};
      insert leads;
        
      // Now make sure that some of these leads can be changed and
      // then bulk updated successfully. Note that lead1 is not
      // being changed, but is still being passed to the update
      // call. This should be OK.
      lead2.Email = 'test2@duptest.com';
      lead3.Email = 'test3@duptest.com';
      update leads;
        
      // Make sure that single row lead duplication prevention works
      // on insert.
      Lead dup1 = new Lead(LastName='Test1Dup',
                           Company='Test1Dup Inc.',
                           Email='test1@duptest.com');
      try {
         insert dup1;
         System.assert(false);
      } catch (DmlException e) {
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 0);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf(
            'A lead with this email address already exists.') > -1);
      }
        
      // Make sure that single row lead duplication prevention works
      // on update.
      dup1 = new Lead(Id = lead1.Id, LastName='Test1Dup',
                      Company='Test1Dup Inc.',
                      Email='test2@duptest.com');
      try {
         update dup1;
         System.assert(false);
      } catch (DmlException e) {
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 0);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf(
            'A lead with this email address already exists.') > -1);
        }
    
      // Make sure that bulk lead duplication prevention works on
      // insert. Note that the first item being inserted is fine,
      // but the second and third items are duplicates. Note also
      // that since at least one record insert fails, the entire
      // transaction will be rolled back.
      dup1 = new Lead(LastName='Test1Dup', Company='Test1Dup Inc.',
                      Email='test4@duptest.com');
      Lead dup2 = new Lead(LastName='Test2Dup',
                           Company='Test2Dup Inc.',
                           Email='test2@duptest.com');
      Lead dup3 = new Lead(LastName='Test3Dup',
                           Company='Test3Dup Inc.',
                           Email='test3@duptest.com');
      Lead[] dups = new Lead[] {dup1, dup2, dup3};
      try {
         insert dups;
         System.assert(false);
      } catch (DmlException e) {
         System.assert(e.getNumDml() == 2);
         System.assert(e.getDmlIndex(0) == 1);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf(
            'A lead with this email address already exists.') > -1);
         System.assert(e.getDmlIndex(1) == 2);
         System.assert(e.getDmlFields(1).size() == 1);
         System.assert(e.getDmlFields(1)[0] == Lead.Email);
         System.assert(e.getDmlMessage(1).indexOf(
            'A lead with this email address already exists.') > -1);
      }
    
      // Make sure that bulk lead duplication prevention works on
      // update. Note that the first item being updated is fine,
      // because the email address is new, and the second item is
      // also fine, but in this case it's because the email
      // address doesn't change. The third case is flagged as an
      // error because it is a duplicate of the email address of the
      // first lead's value in the database, even though that value
      // is changing in this same update call. It would be an
      // interesting exercise to rewrite the trigger to allow this
      // case. Note also that since at least one record update
      // fails, the entire transaction will be rolled back.
      dup1 = new Lead(Id=lead1.Id, Email='test4@duptest.com');
      dup2 = new Lead(Id=lead2.Id, Email='test2@duptest.com');
      dup3 = new Lead(Id=lead3.Id, Email='test1@duptest.com');
      dups = new Lead[] {dup1, dup2, dup3};
      try {
         update dups;
         System.assert(false);
      } catch (DmlException e) {
         System.debug(e.getNumDml());
         System.debug(e.getDmlMessage(0));
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 2);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf(
            'A lead with this email address already exists.') > -1);
        }
        
      // Make sure that duplicates in the submission are caught when
      // inserting leads. Note that this test also catches an
      // attempt to insert a lead where there is an existing
      // duplicate.
      dup1 = new Lead(LastName='Test1Dup', Company='Test1Dup Inc.',
                      Email='test4@duptest.com');
      dup2 = new Lead(LastName='Test2Dup', Company='Test2Dup Inc.',
                      Email='test4@duptest.com');
      dup3 = new Lead(LastName='Test3Dup', Company='Test3Dup Inc.',
                      Email='test3@duptest.com');
      dups = new Lead[] {dup1, dup2, dup3};
      try {
         insert dups;
         System.assert(false);
      } catch (DmlException e) {
         System.assert(e.getNumDml() == 2);
         System.assert(e.getDmlIndex(0) == 1);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf(
            'Another new lead has the same email address.') > -1);
         System.assert(e.getDmlIndex(1) == 2);
         System.assert(e.getDmlFields(1).size() == 1);
         System.assert(e.getDmlFields(1)[0] == Lead.Email);
         System.assert(e.getDmlMessage(1).indexOf(
            'A lead with this email address already exists.') > -1);
      }
        
      // Make sure that duplicates in the submission are caught when
      // updating leads. Note that this test also catches an attempt
      // to update a lead where there is an existing duplicate.
      dup1 = new Lead(Id=lead1.Id, Email='test4@duptest.com');
      dup2 = new Lead(Id=lead2.Id, Email='test4@duptest.com');
      dup3 = new Lead(Id=lead3.Id, Email='test2@duptest.com');
      dups = new Lead[] {dup1, dup2, dup3};
      try {
         update dups;
         System.assert(false);
      } catch (DmlException e) {
         System.assert(e.getNumDml() == 2);
         System.assert(e.getDmlIndex(0) == 1);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf(
            'Another new lead has the same email address.') > -1);
         System.assert(e.getDmlIndex(1) == 2);
         System.assert(e.getDmlFields(1).size() == 1);
         System.assert(e.getDmlFields(1)[0] == Lead.Email);
         System.assert(e.getDmlMessage(1).indexOf(
            'A lead with this email address already exists.') > -1);
      }
   }
}

Thanks!
Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri

Any one please look at this issue

https://developer.salesforce.com/forums/ForumsMain?id=906F0000000D817

Deepak GulianDeepak Gulian
Trigger:-
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){
                leadMap.put(lead.Email, lead);
        }
    }
    
    for (Contact con : [SELECT Email FROM Contact WHERE Email IN :leadMap.KeySet()]) {
        Lead newLead = leadMap.get(con.Email);
        newLead.Email.addError('A Contact with this email '
                               + 'address already exists.');
    }
}

Test Class:-
@isTest
public class leadDupePreventerTests{
    static testMethod void testLeadDupPreventer() {
        
      
      // Account
         Account acc = new Account(
            Name = 'Test Account1'
         );
        insert acc;
      
      // Contacts
      Contact con1 = new Contact( FirstName = 'Fbname', LastName = 'LbName', Email = 'test1@duptest.com', AccountId = acc.Id );
      Contact con2 = new Contact( FirstName = 'Fbname', LastName = 'LbName', Email = 'test7@duptest.com', AccountId = acc.Id );
      Contact[] cons = new Contact[] {con1, con2};
      insert cons;

      // First make sure there are no leads already in the system
      // that have the email addresses used for testing
      Set<String> testEmailAddress = new Set<String>();
      testEmailAddress.add('test1@duptest.com');
      testEmailAddress.add('test2@duptest.com');
      testEmailAddress.add('test3@duptest.com');
      testEmailAddress.add('test4@duptest.com');
      testEmailAddress.add('test5@duptest.com');
      System.assert([SELECT count() FROM Lead
                     WHERE Email IN :testEmailAddress] == 0);
        
      // Seed the database with some leads, and make sure they can
      // be bulk inserted successfully.
      Lead lead2 = new Lead(LastName='Test2', Company='Test2 Inc.',
                            Email='test4@duptest.com');
      Lead lead3 = new Lead(LastName='Test3', Company='Test3 Inc.',
                            Email='test5@duptest.com');
      Lead[] leads = new Lead[] {lead2, lead3};
      insert leads;        
                                          
      // Make sure that single row lead duplication prevention works
      // on insert.
      Lead dup1 = new Lead(LastName='Test1Dup',
                           Company='Test1Dup Inc.',
                           Email='test1@duptest.com');
      try {
         insert dup1;
         System.assert(false);
      } catch (DmlException e) {
         System.debug(e.getDmlMessage(0));
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 0);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf('A Contact with this email address already exists.') > -1);
      }
        
      // Make sure that single row lead duplication prevention works
      // on update.
      lead2 = new Lead(Id = lead2.Id, LastName='Test1Dup',
                      Company='Test1Dup Inc.',
                      Email='test7@duptest.com');
      try {
         update lead2 ;
         System.assert(false);
      } catch (DmlException e) {
         System.debug(e.getDmlMessage(0));
         System.assert(e.getNumDml() == 1);
         System.assert(e.getDmlIndex(0) == 0);
         System.assert(e.getDmlFields(0).size() == 1);
         System.assert(e.getDmlFields(0)[0] == Lead.Email);
         System.assert(e.getDmlMessage(0).indexOf('A Contact with this email address already exists.') > -1);
        }
    
      
   }
}
Update old Trigger with above Trigger!
This was selected as the best answer
Aaron HillAaron Hill
Worked great, Deepak! Really appreciate the help!
Aaron HillAaron Hill
Deepak,

The trigger you provided above worked really well except for one small problem: when I try to convert a lead to a contact the trigger precents that conversion. Could we modify the code so that it allows us to convert contacts into leads?

Much obliged,

-Aaron