Thursday, January 29, 2009

How do I prevent duplicates based on more than one field?

Recently, I had the need to create a unique index based on more than one field.

I required a sObject whose name field is unique for each user. A user can not have two or more records with the same "name", but it is possible for different users to have records with the same name.

Let's suppose I have an sObject with this data:

Owner Name
user1 name1
user2 name2

If "user1" tries to add a row named "name1", the system should prevent him from doing so because "user1" already has a row with "name1". On the other hand if "user2" tries to add a row named "name1" the system should allow this, because "user2" does not have a row named "name1".

My first idea, was to have a formula field that merged the two values and make that formula field be a primary key. But formula fields can not keys.

So I decided on a trigger, and this worked fine...

trigger PreventDuplicateNameForUser on TPName__c (before insert, before update) {
    for (TPName__c TPName : Trigger.new) {
        List<TPName__c> listFound = [SELECT name
                                       FROM TPName__c
                                      WHERE ownerid = :UserInfo.getUserID()
                                        AND name = :TPName.name];
        if (listFound.size() > 0) {
            Trigger.new[0].addError('You already defined a Parameter Name called ['
                                     + TPName.name +']. Please use another name and try again');
        }
    }
}

1 comment:

  1. If a bulk insert is completed this would fail.

    The Salesforce Best Practice is to always bulkify your triggers, so Sets for your SOQL and do not use Trigger.new[0].

    ReplyDelete