Wednesday, February 1, 2012

APEX Trigger to Prevent Duplicate Object Records

One of the biggest issues in Org's that I have seen is with duplicate records. But what is the best way to prevent this? With an easy trigger of course! 


Let take the Contact object, in my Org, everything is keyed off email, so we shouldn't have more than one contact with the same email address. And we need to not only protect against new Contacts, but we also need to ensure that if a User updates the email on the Contact that it too is not already in use before the update occurs. In order for the User to know that they are trying to Insert or Update incorrectly we will have a field error show next to the email of the contact stating that one already exists.


Lets make(or update) a Contact trigger for before insert and before update. 






We are going to use a Map to store the id and email of each contact that comes into the trigger so we can use that to do a SOQL query later when its time to see if it already exists.  add the 'trigger.isBefore' even though we know this will only occur before, so that this can be easily extended in the future and we wont have to go back and change code.




Now we need to populate the map with the Contact info so we can use it in the SOQL query next. We should also send up an error if the batch of Contacts that is being iterated over in the trigger contains more than one of the same email. 




Now that we have the Map populated, or at least in theory it should be, we will query the DB to see if a Contact already exists with that email, and if so, show an error to the User, other wise do nothing and allow it to be inserted/updated. 






And thats it. You can of course make this much more robust, so it not only compares email but also name and phone number too. 


Questions?  
Twitter: @SalesForceGirl  or Facebook

3 comments:

  1. Great post! For additional custom email fields you can also set them to be unique when you build them out. Also you can consider setting custom fields that need to be unique to External Id's since that will index them and make them unique also, but of course you're limited to the number of ExtId's on an object.

    ReplyDelete
  2. Might be this trigger will throw exception due to use of Trigger.Oldmap on before insert event, need to use IsInsert or IsUpdate.

    ReplyDelete
  3. Hi,

    This post is very helpful . Is this concept of avoiding the duplication can be covered by an validation rule.
    so that we can avoid more lines of code .
    As this is the repeating perspective from every object and it may not be much advisable to have a code for each and every object.
    Other than that , the post is very helpful and informative.

    Thank you .
    Anil.

    ReplyDelete