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');
}
}
}
If a bulk insert is completed this would fail.
ReplyDeleteThe Salesforce Best Practice is to always bulkify your triggers, so Sets for your SOQL and do not use Trigger.new[0].