User Story
As a user, when I want to create a new Account, I should not be able to create an Account with the same name as an existing Account. If I try to create an Account with a name that already exists in the system, I should receive a validation error message that the Account name already exists and I need to choose a different name for the new Account. This will help ensure that each Account in the system has a unique name and avoid any confusion or duplicates.
Solution 1
trigger AccountTrigger on Account (before insert) {
Set<String> newListWithName = new Set<String>();
for(Account ac : Trigger.new){
newListWithName.add(ac.Name);
}
list<Account> listofAccounts = [SELECT Id, Name FROM Account WHERE Name in : newListWithName];
for(Account ac : Trigger.new){
if(listofAccounts.size()!=0){
ac.name.addError('An account with the same name is already exists.');
}
}
}
Solution 2
trigger AccountTrigger on Account (before insert, before update) {
Set<String> accountNames = new Set<String>();
for(Account acc : [SELECT Name FROM Account]) {
accountNames.add(acc.Name);
}
for(Account acc : Trigger.new) {
if(accountNames.contains(acc.Name)) {
acc.Name.addError('An account with this name already exists. Please choose a different name.');
}
}
}