Files
Demo1/force-app/main/default/triggers/ValidateAccount.trigger
2025-04-02 17:50:49 +05:30

31 lines
813 B
Plaintext

trigger ValidateAccount on Account (before insert) {
Set<String> accountNames = new Set<String>();
for (Account account : Trigger.New)
{
if (accountNames.contains(account.Name))
{
account.Name.addError('Account name already exists!');
}
else {
accountNames.add(account.Name);
}
}
List<Account> existingAccounts = [
SELECT Id, Name
FROM Account
WHERE Name IN :accountNames
];
for (Account account : Trigger.New)
{
for (Account existingAccount : existingAccounts)
{
if (account.Name == existingAccount.Name && account.Id != existingAccount.Id)
{
account.Name.addError('Account name already exists!');
}
}
}
}