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.
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?
ReplyDeleteThis is not correct
ReplyDeleteThis is not correct. This will work on before delete
ReplyDeleteAbove is incorrect, this will work with "before delete" and not with "after delete"
ReplyDeletehi!.....
ReplyDeletebefore 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.