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 and is linked to account using lookup Account__c.

APEX TRIGGER:

trigger AccountMainTrigger on Account (after delete) { 
    if (Trigger.isAfter && Trigger.isDelete) {
        AccountMainTriggerHandler handler = new AccountMainTriggerHandler();
        handler.deleteChildRecords(Trigger.old); // Passing deleted Account records to the handler method
    }
}


APEX CLASS:

public class AccountMainTriggerHandler {

    public void deleteChildRecords(List<Account> accList) {
        // Collecting Account IDs from the deleted Account records
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : accList) {
            accountIds.add(acc.Id); // Adding Account IDs to the set
        }

        // Querying all related child records (Child_object__c) based on Account IDs
        List<Child_object__c> childRecords = [SELECT Id FROM Child_object__c WHERE Account__c IN :accountIds];

        // If there are child records, delete them
        if (!childRecords.isEmpty()) {
            try {
                delete childRecords; // Bulk DML delete operation
            } catch (DmlException e) {
                // Handle DML exception if necessary (e.g., logging or error handling)
                System.debug('Error during child record deletion: ' + e.getMessage());
            }
        }
    }
}


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

Let us understand with another exaple,

Let's create an AFTER DELETE trigger for the Opportunity object in Salesforce. This trigger will log the details of deleted Opportunity records into a custom object called OpportunityAudit__c for auditing purposes.

Create the Custom Object

First, create a custom object OpportunityAudit__c with the following fields:

  • Opportunity Name (Text)
  • Opportunity Stage (Text)
  • Opportunity ID (Text)
  • Deleted At (Date/Time)

trigger OpportunityAfterDelete on Opportunity (after delete) {

 

    // List to store OpportunityAudit__c records

    List<OpportunityAudit__c> opportunityAudits = new List<OpportunityAudit__c>();

 

    // Loop through the deleted Opportunity records

    for (Opportunity opp : Trigger.old) {

        // Create a new OpportunityAudit__c record for each deleted Opportunity

        OpportunityAudit__c auditRecord = new OpportunityAudit__c(

            Opportunity_Name__c = opp.Name,

            Opportunity_Stage__c = opp.StageName,

            Opportunity_ID__c = opp.Id,

            Deleted_At__c = System.now() // Timestamp when the Opportunity was deleted

        );

 

        // Add the audit record to the list

        opportunityAudits.add(auditRecord);

    }

 

    // Insert the audit records into the OpportunityAudit__c object

    if (!opportunityAudits.isEmpty()) {

        insert opportunityAudits;

    }

}

 




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