Monday, October 28, 2019

WHAT IS BEFORE DELETE EVENT IN APEX TRIGGER, EXPLAIN IT WITH AN EXAMPLE?


BEFORE DELETE:

This event runs the block of code before the data is deleted from the database. Operations such as preventing data deletion from the database can be handled using this event.

SYNTAX:

trigger triggerName on objectName (before delete) {
   // Block of code
}

SCENARIO:

We are having the requirement to prevent deletion of Account record if it has parent Account associated with it.

APEX TRIGGER:

trigger AccountDeletionTrigger on Account (before delete) {
    if (Trigger.isBefore && Trigger.isDelete) {
        AccountDeletionHandler handler = new AccountDeletionHandler();
        handler.checkParentAccount(Trigger.old); // Passing records to Apex handler method
    }
}

APEX CLASS:

public class AccountDeletionHandler {
    
    public void checkParentAccount(List<Account> accountList) {
        // Loop through the list of accounts to check for parent relationships
        for (Account acc : accountList) {
            if (acc.ParentId != null) { // Check if the account has a parent account
                acc.addError('You cannot delete this account because it is associated with a parent account. Please remove the relationship between the accounts first before deleting this account.');
            }
        }
    }
}


Now, let us try to delete an account record that has a parent account associated with it.

before delete trigger salesforce
before delete trigger salesforce example
how to write before delete trigger in salesforce

2 comments:

  1. Is it possible to show the custom error message in a toast instead of modal?

    ReplyDelete
  2. Is it possible to store the count number of times we tried to delete the record on account object.

    ReplyDelete