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

5 comments:

  1. I have tried this scenario but it seems that Account__c field will be blank in case on After Delete so we will not get any records. I have tried this scenario. can you please double confirm on the same?

    ReplyDelete
  2. This is not correct. This will work on before delete

    ReplyDelete
  3. Above is incorrect, this will work with "before delete" and not with "after delete"

    ReplyDelete
  4. hi!.....
    before delete allows records to delete
    whereas after delete blocks cascading and deletion of records ...

    before insert and update .......is used for same kind of object record
    after insert and update ..........is used for different kind of object records.

    ReplyDelete