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 AccountMainTrigger on Account (before delete) { // Specifying the event.
    createContactClass obj=new createContactClass(); // Creating instance of the class.
    if(trigger.isbefore && trigger.isdelete) // Using context variable.
    {
     obj.method1(Trigger.old); // Passing records to apex method.
    }
}

APEX CLASS:

public class createContactClass {
    public void method1(List<Account> accList){ // Getting the list of the account.
        for(Account acc:accList){
            if(acc.ParentId!=null){ // Checking if the account has a parent account associated to it.
                acc.addError('you cannot delete this account as it is associated with the parent account. Please remove relationship between accounts first to delete this account record.'); // Throw error if the condition is satisfied.
            }
        }
      
    }
}

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

No comments:

Post a Comment