When user tries to insert Account with name which already used in another existing account ,User should be presented with Error.
There are multiple approach to do same question: Let’s learn each approach to improve our coding skills:
WAY1
trigger AccountDuplicateCheckTrigger on Account (before insert) { //Preparing Account names in Set from trigger.new Set<String> nameSet = new Set<String>(); for(Account acc : trigger.new){ nameSet.add(acc.name); } // getting the list of accounts in database with the account name we entered ( trigger.new) List<Account> accList = new List<Account>([select id,name from Account where name in: nameSet]); for(Account a : trigger.new){ if(accList.size() > 0 ) a.addError('Account already exists in your Organization with name '+a.name); } }
WAY2: Check Using null condition
trigger DemoTrigger on Account(before insert,before update) { List<Account> accList=new List<Account>([select id,name from Account]); map<String,Account> accmap=new map<String,Account>(); for(Account acc:accList){ accmap.put(acc.Name,acc); } for(Account acc:Trigger.new){ if(accmap.get(acc.Name)!=null){ acc.adderror('Name already exists'); } } }
WAY3: Check using containsKey condition
trigger DemoTrigger on Account(before insert,before update) { List<Account> accList=new List<Account>([select id,name from Account]); map<String,Account> duplicateMap=new map<String,Account>(); //get old records for(Account acc:accList){ duplicateMap.put(acc.Name,acc); } //compare old records with records in trigger.new for(Account acc:Trigger.new){ if(duplicateMap.containsKey(acc.Name)){ acc.adderror('Name already exists'); } } }
Test Class
@istest public class AccountduplicateTriggerTest{ static testmethod void myTest(){ Boolean result =false; Account acc = new Account(); acc.Name= 'Smriti'; insert acc; try{ Account acc1=new account(); acc1.Name= 'Smriti'; insert acc1; } catch(DMLException ex) { result=true; system.assert(result); } } }
https://developer.salesforce.com/forums/?id=906F000000094I7IAI
https://developer.salesforce.com/forums/?id=9060G000000XbWPQA0