Header Ads Widget

Trigger Scenario 3 on before insert and before update with trigger.new, duplicate records are not allowed while creating and updating a record


Trigger Scenario 3 on before insert and before update with trigger.new, duplicate records are not allowed while creating and updating a record

Trigger Scenario 3

The following trigger will fire when we try to create the account with same name i.e. preventing the users to create Duplicate Accounts.

Trigger:



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

    for(Account a:Trigger.New){

        List<account> acc=[Select id, Name from Account where Name =: a.Name];

        if(acc.size()&gt;0){

            a.Name.addError('You Cannot create the Duplicate');

        }

    }

}

How to see Output:



Before insert:

Step1:

Remember a saved Account record (like “Mahesh”).

Click on New button to create a record.



Step2:
Fill any duplicate value (like “Mahesh”) in Account Name Field and click on save. It shows error message. It does not save.

Before Update:
Step1
Now fill without duplicate value and save that record or open any saved account record


Step2
Click on edit button and save with duplicate value again it shows error message. It does not save. It saves without duplicate value only.
Test Class:
@istest
public class DuplicateAccountTestClass {
    public static @istest void testAccountDuplicateTrigger(){
       String addError;
        Account a1 = new Account(Name='Test Account');
        insert a1;
        Account a2 = new Account(Name='Test Account');
        insert a2;
        system.assertEquals('You can create duplicate Account', addError);
        try{
            insert a2;
        }
        catch(Exception e){
            System.debug('We want to see this. This
                       means the trigger is working.');
        }
    }
}


Post a Comment

0 Comments