2

I am trying to prevent duplicate users while creating the record in custom object which is having look-up relationship. The code is executing fine in before insert, But when updating same record with different field values it is showing the error, I want to show the error when the user modifies non-existing user to existing user only.

Can i achive with the following trigger or can i go for another concept?

trigger PreventDuplicateUser on object__c(before insert,before update) {
    for(object__c o:trigger.new)
    {
        list<object__c> obj=[select id,user__c from object__c where user__c=:o.user__c];
        if(obj.size()>0)
        {  
            r.addError('Duplicate users not allowed');
        }
    }

}
2
  • You can add this to your trigger to exclude the current object in the SOQL query : [select id,user__c from object__c where user__c=:o.user__c and id not in: :trigger.new ];
    – user28829
    Commented May 18, 2017 at 11:53
  • @Merabti Ibrahim , Thank you for your solution. Your answer solved my question. Thank you.. Commented May 18, 2017 at 18:06

1 Answer 1

1

This is an adaptation of my code from a previous question, which I did not flag this question as a duplicate because the other answer was more appropriate for that question.

Basically, to be truly bulkified, we have to (a) detect duplicates in the current trigger context, then detect any duplicates elsewhere in the database. Note that multiple duplicates in the same transaction will all be flagged as duplicates, and will have to be reloaded separately. This is intentional, as it allows you to determine which record you want to use.

trigger preventDup on User (after insert, after update) {
    Map<String, Id> userNameToId = new Map<String, Id>();
    for(User record: Trigger.new) {
        if(userNameToId.containsKey(record.User__c)) {
            record.addError('Duplicate user not allowed.');
        } else {
            userNameToId.put(record.User__c, record.Id);
        }
    }
    for(User record: [SELECT User__c FROM User WHERE User__c IN :userNameToId.keySet() FOR UPDATE]) {
        if(userNameToId.get(record.User__c) != record.Id) {
            Trigger.newMap.get(userNameToId.get(record.User__c)).addError('Duplicate user not allowed.');
        }
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .