0

Want to restrict the duplicate account. I tried with the below code. It is working fine on insert and not working on update. When I edit any account record it is giving error as duplicate. Can any one help me out what changes I need to make in my code.

Here is my trigger:

trigger DuplicateAccount on Account (before insert,before update) {
    Set<string> accname = new Set<string>();
    Set<string> duplicateAccIds = new Set<string>();

    for(account acc:Trigger.new){
        accname.add(acc.name);
    }
    list<account> duplicateAcclist = [SELECT id, name FROM account WHERE name=:accname];
        for(account dup:duplicateAcclist){
            duplicateAccIds.add(dup.name);
        }
    for(account a:trigger.new){
        if(a.name != null){
            if(duplicateAccIds.contains(a.name)){
                a.addError('Record already exist with same name');
            }
        }
    }
}
0
4

The problem that you have is the fact that you are actually querying the same account at update.

So, for example:

  • You have an account(A1) with name testAcc and you update some field
  • Trigger fires on update
  • You query accounts WHERE Name = 'testAcc'
  • Aaaaand... You get that A1 in your query!
  • As the result, you will addError() on A1 which will prevent it from being updated

So you should make sure that that same account A1 will not be in your query, otherwise you will always get an error(except for when you change the name of the account).

Also, why don't you use standard duplicate management? Don't forget: Code that you do not write is the code you do not have to maintain

3
  • Ok Thanks for your reply.. So how can I do it on update..? – user41260 Feb 1 '17 at 7:35
  • 2
    @user41260 Use duplicate management. There's no need to do this in code any longer. – sfdcfox Feb 1 '17 at 7:53
  • Thanks a lot yar.. I just gone through that duplicate management. Its really help me alot. Thanks again guys. – user41260 Feb 1 '17 at 10:52

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.