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
LBartonLBarton 

Preventing Contacts from Duplicating Leads Except When Being Converted

I want to avoid contacts from having the same email address as a lead except in the situation where a user is manually converting a lead.  I have modified the cookbook code used to avoid duplicates and tried adding

 

if (lead.IsConverted == false )

 

However, this is not doing what I want.  Evidently it is seeing if the lead has been converted but not if it is currently abut to be converted. Thanks for your help!  Here is the code:

 

 

trigger

PreventDuplicateContact onContact (beforeinsert, beforeupdate) {

 

  Try {

   Map<String,

Contact> contactMap = new Map<String, Contact>();

   

for (Contact contact : System.Trigger.new)  {

       

       

// Make sure we don't treat an email address that 

       

// isn't changing during an update as a duplicate.

   

       

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

                (System.Trigger.isInsert ||

                (contact.Email !=

                    System.Trigger.oldMap.

get(contact.Id).Email))) {

       

           

// Make sure another new contact isn't also a duplicate 

   

           

if (contactMap.containsKey(contact.Email)) {

                contact.Email.addError(

'A record with this email address already exists as a Lead or Contact.');

            }

           

else {

                contactMap.put(contact.Email, contact);

            }

       }

    }

   

   

// Using a single database query, find all the contacts in 

   

// the database that have the same email address as any 

       

// of the contacts being inserted or updated. 

   

   

for (Contact contact : [SELECT Email FROM contact

                     

WHERE Email IN :contactMap.KeySet()]) {

       

Contact newContact = contactMap.get(contact.Email);

        newContact.Email.addError(

'A record with this email address already exists as a Lead or Contact.');

    }

   

for (Lead lead : [SELECT Email FROMLead

                    

WHERE Email IN :contactMap.KeySet()]) {

      

if (lead.IsConverted == false ) {

           

Contact newContact = contactMap.get(lead.Email);

            newContact.Email.addError(

'A record with this email address already exists as a Lead or Contact.');

       }

    } 

       

   

  }

 

catch (exception e){

  } 

 

}

Coco_SdyneyCoco_Sdyney

Will need to write trigger on Lead object to catch up duplicate when it's about to be converted, like this:

 

trigger catchDupe on Lead (before update){

for(Lead l : trigger.new)

{

 

if(l.IsConverted)

{

 

// do something here

 

}

}

}