+ Start a Discussion

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

I need to have an sObject where the 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 me explain....
Let's suppose I have an sObject with this data:
Owner   Name
user1  name1
user1  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".
So far, I have come to this solution... But I would like to know if there is a better any of doing it.
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');
} }

 One of the things that concern me is that triggers are not always fired.
Is there a better way of doing this... I mean is there something to configure in a sObject to make it behave like this?
What do you mean, triggers are not always fired?  They are always fired when you make an insert or update.

I was reading the document "APEX Language Reference", and I found this:

 Trigger-Ignoring Operations

Triggers are only invoked for data manipulation language (DML) operations that are initiated or processed by the Java application server. Consequently, some system bulk operations do not currently invoke triggers. Some examples include:

  • Cascading delete operations. Records that did not initiate a delete do not cause trigger evaluation.
  • Cascading updates of child records that are reparented as a result of a merge operation
  • Mass campaign status changes
  • Mass division transfers
  • Mass address updates
  • Mass approval request transfers
  • Mass email actions
  • Modifying custom field data types
  • Renaming or replacing picklists
  • Managing price books

I guess it does not affect my simple cases, but it got me wondering if there was a better way of doing the multiple field unique constran, which is so common in databases.