Posts

Showing posts from May, 2022

Trigger Scenario 8 : Preventing the users to create Duplicate Accounts

Image
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