Trigger 4 - Trigger to prevent duplication of an Account record based on Name whenever a record is inserted or updated.
Trigger 4 scenario - Trigger to prevent duplication of an Account record based on Name whenever a record is inserted or updated.
trigger AccountTrigger on Account (before insert, before update) { if (Trigger.isBefore) { if (Trigger.isInsert) { AccountTriggerHandler.preventDuplicateNames(Trigger.new, null); } else if (Trigger.isUpdate) { AccountTriggerHandler.preventDuplicateNames(Trigger.new, Trigger.oldMap); } } }
public class AccountTriggerHandler {
public static void preventDuplicateNames(List<Account> newAccounts, Map<Id, Account> oldAccountMap) {
Set<String> newAccountNames = new Set<String>();
List<Account> recordsToValidate = new List<Account>();
// 1. Isolate the names being added or changed
for (Account acc : newAccounts) {
if (acc.Name != null) {
// If inserting, or updating to a new/different name
if (oldAccountMap == null || acc.Name != oldAccountMap.get(acc.Id).Name) {
newAccountNames.add(acc.Name);
recordsToValidate.add(acc);
}
}
}
// 2. Query existing accounts in the database with these names
if (!newAccountNames.isEmpty()) {
Set<String> existingNamesInDb = new Set<String>();
for (Account existingAcc : [SELECT Name FROM Account WHERE Name IN :newAccountNames]) {
existingNamesInDb.add(existingAcc.Name.toLowerCase());
}
// 3. Track duplicates within the same batch (e.g., bulk upload containing duplicates)
Set<String> namesInCurrentBatch = new Set<String>();
// 4. Compare and throw error if a match is found
for (Account acc : recordsToValidate) {
String currentNameLower = acc.Name.toLowerCase();
if (existingNamesInDb.contains(currentNameLower) || namesInCurrentBatch.contains(currentNameLower)) {
acc.Name.addError('An Account with the name "' + acc.Name + '" already exists.');
} else {
namesInCurrentBatch.add(currentNameLower);
}
}
}
}
}
Comments
Post a Comment