Monday, October 28, 2019

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


AFTER DELETE:

This event runs the block of code after the data is deleted from the database. Operations such deleting related records can be handled using this event.

SYNTAX:

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

SCENARIO:

We are having the requirement to delete the child object records associated with Account record when the Account record is deleted. “Childobject” is a related list on Account.

APEX TRIGGER:

trigger AccountMainTrigger on Account (after delete) { // Specifying the event.
    createContactClass obj=new createContactClass(); // Creating the instance of the apex class.
    if(trigger.isafter && trigger.isdelete) // Using context variable.
    {
     obj.method1(Trigger.old);  // Calling apex class method.
    }
}

APEX CLASS:

public class createContactClass {
    List<Child_object__c> cObjToDeleteList=new List<Child_object__c>();
    public void method1(List<Account> accList){ // Getting list of account records.
        for(Account acc:accList){ // Iterating over account list.
            for(Child_object__c cs:[Select id from Child_object__c where Account__c=:acc.id]){
                cObjToDeleteList.add(cs); // Adding related child object associated to an account in a list.
            }
        }
        if(cObjToDeleteList.size() > 0){ // Checking if the list contains records.
            delete cObjToDeleteList; // Deleting records.
        }
      
    }
}

Now let us try to delete an account record which has a child object associated with it as shown in the below image.

after delete trigger salesforce

    
after delete trigger in salesforce
    
after delete trigger example in salesforce

after delete trigger salesforce example

No comments:

Post a Comment