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];
            r.addError('Duplicate users not allowed');

  • 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 ]; – Merabti Ibrahim May 18 '17 at 11:53
  • @Merabti Ibrahim , Thank you for your solution. Your answer solved my question. Thank you.. – Ravindar Admin May 18 '17 at 18:06

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.');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.