Skip to main content

Command Palette

Search for a command to run...

Trigger Scenario 1

Published
•1 min read•View as Markdown

Write the trigger to prevent the deletion of Account Record whose Active__c = ‘Yes’ [Active__c is custom picklist having Yes, No as Values] and show the error message as “You can not delete this Account, As this Account still active”.
Make sure create Trigger, TriggerHandlerClass and test class to verify trigger is working fine.

AccountTrigger.apxt

trigger AccountTrigger on Account (after insert, before delete) {

    if(trigger.isBefore && trigger.isDelete){
        AccountTriggerController.beforeDelete(trigger.old);
    }
}

AccountTriggerController.apxc

public with sharing class AccountTriggerController {
    public AccountTriggerController() {
    }

    public static void beforeDelete(List<Account> lstAccounts) {
        for(Account acc: lstAccounts){
            if(acc.Active__c == 'Yes'){
                System.debug('Account is active cannot be deleted: '+acc);
                acc.addError('You can not delete this Account, As this Account still active');
            }
        }
    }
}

AccountTriggerControllerTest.apxc

@isTest
private class AccountTriggerControllerTest {
    @isTest
    static void testBeforeDelete() {

        List<Account> lstAccounts = [SELECT Id, Name, Active__c FROM Account ];

        Test.startTest();
        try {
            delete lstAccounts;
        } catch (Exception e) {
            String expectedErrorMessage = 'You can not delete this Account, As this Account still active';
            Assert.isTrue(e.getMessage().contains(expectedErrorMessage));
            system.debug('Error Message: '+e.getMessage());
        }
        Test.stopTest();

        List<Account> remainingAccounts = [SELECT Id FROM Account WHERE Id = :lstAccounts[0].Id];
        System.assertEquals(1, remainingAccounts.size());
    }

    @TestSetup
    static void makeData(){
        Account activeAccount = new Account(Name = 'Active Account', Active__c = 'Yes');
        insert activeAccount;
    }
}