Salesforce Apex Trigger | Part 3

salesforce apex triggers by salesforce kid delete, update triggers

Salesforce Apex Trigger | Part 3

In Previous EPISODES we discussed how to write Insert and Update triggers in Salesforce.
In this episode, we are going to discuss how to write DELETE triggers in salesforce.

So let's get started...

Types Of Delete Events 
There are two types of delete events :
1. Before Delete
2. After Delete

Trigger.old in Before or After delete : 
This will store the list of records which are already present in your database. Meaning that you are performing the delete operation on existing records in Salesforce.

This will store the list of records which we are trying to delete.

Let's consider the following example :

| CID | Name | Age | Phone |
| 111 |  aaa    | 23    | 3455    |
| 222 | bbb    | 34     | 2344    |
| 333 | ccc     | 27     | 9876    |
| 444 | ddd    | 56     | 2346    |  

On these records, we can only perform read-only operations.

If we are trying to delete 

| 333 | ccc     | 27   | 9876     |
| 444 | ddd    | 56   | 2346     |  

Then Trigger.old will contain there two records.

Now let's consider a scenario-based example to understand this clearly.

Scenario 1 :
When we are trying to delete customer record delete all the corresponding child records from a Test object. Where Customer is a lookup field in the loop object.

Trigger :
trigger CustomerUpdate on Customer__c (after delete)
 List<Test__c> test = [SELECT Id FROM Test__c WHERE CDetails IN :                                            Trigger.old];
 delete  test;
Now what you will do when you want to perform after undelete

EVENT: After Undelete
When we undelete the records from the recycle bin. This operation is written in after undelete will be performed.

Trigger.New : 
This will store the records which we have undeleted are stored in Trigger.New

Have a look at the following trigger when you want to check when the case is just undeleted and update the list.

Trigger :
trigger caserecundel on Case (after undelete) {

    if( trigger.isundelete){
     // Get Cases just un-deleted

      list<Case> casesUnDeleted = new list<Case>();

      casesUnDeleted = [SELECT id,After_Undelete__c FROM Case                                                    WHERE Id IN :trigger.newmap.keyset()];  

      for(Case c :casesUnDeleted) {

        c.After_Undelete__c = true;


      update casesUnDeleted;

In the above trigger, first we are creating instance on a list of case casesUnDeleted then we have written query to fetch all the data to get cases which are just undeleted from the database of the salesforce.

Then It is checking for every case when it's undeleted then it is updating the database

Now I would also like to discuss when to use Trigger.NewMap and Trigger.oldMap

A map of IDs to the new versions of the sObject records. 
Note that this map is only available in before update, after insert, and after update triggers.

A map of IDs to the old versions of the sObject records. 
Note that this map is only available in update and delete triggers. 

Let's understand this with a real-time scenario with the help of an example

Scenario :
Whenever we try to update the phone of account record then update the related contact phone no. with the new account phone no. before account record is updated.
When we delete the account record then delete the corresponding Contact records.
trigger ContactUpdate on Account(before update, after delete)
 if(Trigger.isBefore && Trigger.isUpdate)
   Map<Id,Account> mymap = Trigger.newMAp;
   List<Contact> con = new List<Contact>();

   List<Contact> con = [SELECT Id, phone, accountId FROM Contact                                                WHERE accountId IN : mymap.keyset()];

  for(Contact c : cons)
  { = mymap.get(c.accountId).phone;
update con;

 if(Trigger.isAfter && Trigger.isDelete)
   Map<Id, Account> deleteacc = Trigger.oldMap;
  List<Contact> myContact = [SELECT Id FROM Contact WHERE                                                                 AccountId IN: deleteacc.keyset()];
 delete myContact;

Explanation :

Part 1 :
In the above trigger first, it will check whether the event is before and update by Trigger.isBefore && Trigger.isUpdate then it will proceed further.

Then we have created Map which contains key= Id and value= Account type which is equal to the  Trigger.NewMap which is actually storing all the new entries. Meaning that it will only contain the Id of new accounts only.

Hence it will perform DML operations on new records.

Then we have written SOQL query for contacts under that account
SELECT Id, phone, accountId FROM Contact WHERE accountId IN : mymap.keyset()
To get all the keyset() from an instance of newMap i.e. mymap

Then it will equal the phone no. of a new account and update the same for all the contacts under that account.

Part 2 :
Then in the second part of the above code, it will check for an after delete event by using Trigger.isAfter && Trigger.isDelete

Then we have created an instance of a map deleteacc which will store Ids of old account present in database hence its equal to Old values i.e. Trigger.oldMap

Then we have written a simple query to fetch all the contacts under that account. 
When an account is deleted all the contacts under that will be deleted with delete myContact

I hope you understand above breakdown of all the above trigger.

Now let's understand the Order of execution of triggers 

NOTE: This is very important from all the aspects to understand what will happen when you hit on save button in salesforce 

Order Of Execution In Salesforce
When we save a record with an Insert, Update or Upsert statement in salesforce performs the events in order.
When an event happens, the order of execution is very important because they are multiple things on a single event and when gets fired we need to know which process is running first and which process is running last 

The order of execution of trigger is in the following order

1. Executes all before triggers
2. System validations are performed
3. Custom Validations are performed
4. Saves the record but doesn't commit
5. Executes all after triggers
6. Executes assignment rules
7. Executes auto-response rules
8. Executes workflow rules
9. If the record was updated with workflow field updates, fires before and after triggers one more time in addition to Standard validations. Custom validation rules not run again
10. Executes escalation rules
11. Commits to the database

Every record follows the above execution order on click on submitting of record.

In the next episode, we will discuss some real-time scenarios and then Recursive Triggers in salesforce.


If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)

<< PREVIOUS                                                    NEXT >>

salesforce kid on play store

Salesforce Apex Trigger | Part 3 Salesforce Apex Trigger | Part 3 Reviewed by on Rating: 5

1 comment:

  1. Anonymous9/30/2020

    Scenerio First you can use like this also...........

    public class beforeInsertUpdate_helper {
    public static void AfterInsertAccount(List triggerNew){
    mapacMap= new map();
    set acOwnerId= new set();
    for(Account ac:triggerNew){
    Mapusermap = new Map([SELECT Name FROM user WHERE Id IN:acOwnerId]);
    for(account a : acMap.values()){
    user uss= usermap.get(a.OwnerId);;




Powered by Blogger.