Thursday, July 28, 2022

How to prevent duplicates on account object by Trigger

 trigger AccountDuplicateTrigger on Account (before insert,before update) {

    list<string> accountNames=new list<string>();
    for(Account accountVar:trigger.new)
    {
        accountNames.add(accountVar.name);
    }
    list<Account> listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
    for(Account account:trigger.new)
    {
        if(trigger.isInsert){
        if(listOfDuplicateAccounts.size()!=0)
        {
            account.addError('Account already exists with this name');
        }
        }
        if(trigger.isUpdate)
        {
           for(Account oldaccount :trigger.old)
           {
               if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0)
               {
                   account.addError('Account already exists with this name');
               }
           }
        }
    }
    

}

No comments: