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
RivoRivo 

Duplicate Contact Trigger

I am attempting to implement a trigger that prevents duplicate contacts from being added.

 

Being a non developer (mere admin) I have download the app from the AppEx and although this gets me 90% of the way, I need to enhance the logic to include "Account Name". I have used a bit of trial and error (blantent guess work) but to no avail.

 

Below is the the apex trigger, but how do I include "Account"??

 

 

trigger ContactDuplicateTrigger on Contact (before insert) {
   for (Contact c : Trigger.new){
      
      Contact[] contacts= [select id from Contact where FirstName = :c.FirstName and LastName = :c.LastName and Email = :c.Email];
      
      if (contacts.size() > 0) {
          c.LastName.addError('Contact cannot be created - Contact already exists');
      }    
   }
}

 

Additionally I know that you need to test the trigger using an Apex Class, which of course I have, but wouldn't know how to tie in the changes above with below....if that makes sense.?!"

  

public class DuplicateContactTestClass {
   
   public static testMethod void testContactDuplicateTrigger() {
    Contact existingContact = new Contact(FirstName = 'John', LastName = 'Smith', Email = 'js@gmail.com');
    insert existingContact;
    
    Contact duplicateContact = new Contact(FirstName = 'John', LastName = 'Smith', Email = 'js@gmail.com');
    try {
       insert duplicateContact;
    }
    catch (Exception e) {
       System.debug('We want to see this.  This means the trigger is working.');
    } 
   }
}

 

 Help!!!

jkucerajkucera

This trigger will break any time you do a mass update (such as in a list view) of more than 20 contacts at once as you have a query in a loop and apex limits you to 20 queries total in a save.  It's harder to write, but saves you headaches later.

 

Check out this document for best practices on bulkifying

http://wiki.developerforce.com/index.php/Best_Practice:_Bulkify_Your_Code

 

Back to your original question - how to add Account.Name - you can use similar logic to add the name to the 3 fields to be checked for dupes. 

 

That said - won't email address be enough? Any reason you'd want 2 John Smith's in 2 different accounts?

 

RivoRivo

Thanks for the response....

 

Believe it or not we do have bonefide dupes, whereby we have Accounts that have differing legal entities but are part of the same group. Then there are contacts that cross these multiple accounts (hope this makes sense!). This is a problem within itself and as yet I have yet to come up with an alternative solution - other than to add duplicates.

 

Back to the case in point, I want to prevent users from adding duplicate contacts into the same account, thus my original question about adding Account. This said what makes a contact unique is email address, so I could perhaps dispense with first name, last name and have the trigger driven by Account and Email ??

 

 

jkucerajkucera

Yeah - email + Account Name should be enough.

D S.ax1052D S.ax1052

 

Hi,

 

Have you got the solution to avoid duplicates contacts under one account?

 

Please post the same. It would be useful.

 

Cheers,

D S

bboschebbosche

I'd like to see that final code too.

 

Bob

RivoRivo

It's a bit clunky, but it works which is the main thing.....:smileyhappy:

In the Contacts object create a new text field "DUPLICATE PREVENTOR" with the 'unique' attribute enabled. This field will be used to contain a unique string. I remove this field from the screen layout.

Create a workflow rule that is triggered when a contact record is created or edited and when the Email Address not equal to null i.e. always.

The workflow action should be a field update of the "DUPLICATE PREVENTOR" field.

The field update value should be a formula. I use this one:

Account.Name & FirstName &  LastName & Email

The last task it to populate the "DUPLICATE PREVENTOR" field of all existing contact records. I did by creating a report that contains Contact.Id and Telephone number. Using Data Loader I re-ran the data back into SFDC, thus editing the record and therefore triggering the workflow rule. Obviously I recommend running this out of hours, just in case the user edits the telephone number.

Hope this helps.

 

 

DoondiDoondi
from 2011 to 2017 is there any hero who can post code here?? 
Angie ShonaAngie Shona
Hi, try this
trigger DupCon on Contact (before insert, before update) {

    set<String> EmailIds = new set <String> ();

    for( Contact con : Trigger.new)
    {
        emailIds.add(Con.Email);
    }
List<Contact> listCon = [SELECT Id, Name, Email FROM Contact WHERE Email in :emailIds];

set<String> existingEmail = new set<string> ();

for( Contact con: listCon)
{
    existingEmail.add(Con.Email);

    }
for( Contact con: Trigger.new){
    if(existingEmail.Contains(con.Email))

    {
        con.AddError('Duplicate contact found, Please use another email id');
    }
}
}


Regards,
Angie