Trigger Scenario 8 : Preventing the users to create Duplicate Accounts
Trigger Scenario 8 :
The following Trigger will fires when we try to create the account with same name i.e. Preventing the users to create Duplicate Accounts
Object : Account
Trigger: Before Insert, Before Update
MIND IT !
Here (Way-1), I have used SOQL inside for loop which will affect governor limit and it is not best practice.
The most important being that it is not bulkified. We should always avoid SOQL inside loop. So please see second way-2 below for best practices.
WAY-1
Trigger Code: AccountDuplicateTrigger.apxt
1 2 3 4 5 6 7 8 9 10 | trigger AccountDuplicateTrigger on Account (before insert, before update) { for (Account a:Trigger. new ) { List<Account> acc=[select ID from account where Name=:a.Name and Rating=:a.rating]; if (acc.size()> 0 ) { a.adderror( 'You cannot create a duplicate account' ); } } } |
Test Class: AccountDuplicateTriggerTest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @istest public class AccountDuplicateTriggerTest{ static testmethod void myTest(){ Boolean result = false ; Account a = new Account(); a.Name= 'Yuvarajxp' ; a.Rating= 'Warm' ; insert a; try { Account a1= new account(); a1.Name= 'Yuvarajxp' ; a1.Rating= 'Warm' ; insert a1; } catch (DMLException ex) { result= true ; system. assert (result); } } } |
WAY-2
Here, avoid SOQL Queries or DML statements inside FOR Loops
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | trigger AccountDuplicateTrigger on Account (before insert, before update) { list<string> acc = new list<string>(); for (Account a:Trigger. new ) { acc.add(a.name); } list<Account> listOfDuplicateAccounts = [select id, Name from Account where Name in :acc]; 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' ); } } } } } |
Comments
Post a Comment