Hello folks in this blog post we’ll go deeper into apex trigger. If you want to learn basics of trigger then go to Salesforce Trigger Basics
This blog is targeted to people who are newbies and for Admins who are targeting to learn development.
Topics Covered
- Trigger Scenario
- Governor Limit
- Code Bulkification
- Order of Execution
I’ll start by Introducing myself, I’m Abhishek Chopra working as a Salesforce Developer with 4.5 yrs. Experience, I’m a Platform Developer 1 Certified professional so you can trust me when you read through my blog post. So, let’s gets started.
Let’s take example where we will see how After Trigger Works
Scenario: – Create a follow up Task on the Opportunity record when the Opportunity stage is set to ‘Closed Won’.
Following the same steps to create a trigger
Developer Console -> Apex -> New -> Apex Trigger
- Giving any logical name and the object on which the Trigger has to operate, this time it would be Opportunity.
- Copy the below logic in the Trigger you just created. (Don’t worry I’ll explain every bit and line of it).
============================================================
List<Task> tskList = new List<Task>(); for(Opportunity opp : Trigger.new) { if(opp.StageName == 'Closed Won') { Task tsk = new Task(WhatId = opp.Id , Subject = 'Follow up Task- Opportunity Closed Won', Priority = 'High'); tskList.add(tsk); } } if(tskList.size() > 0) { insert tskList; }
Hence your Trigger should look something like below: –
Line 1: – It’s a boilerplate code that you get when you create a brand-new Trigger. You just have to adjust in what events it should run. You can add events in a Comma separated fashion.
Line 3: – Initialization of List collection of type ‘Task’. You would have noticed it has its use in Line 12 of the code. So, let’s first understand what is the significance of collections in APEX.
People would have iterated you millions of times that Salesforce is a multitenant(shared) environment and it enforces limits on the resources you can use. So let’s take aside some time and understand what are some of the important limits we should always eye on while coding in APEX.
Description | Limit |
Total number of DML statements issued | 150 |
Maximum number of queries you can initiate | 100 |
Maximum number of rows you can fetch in a SOQL | 50,000 |
Limit on number of SOSL query you can issue | 20 |
Maximum number of records you can fetch in a SOSL query | 2,000 |
We could have written the same code as below.
Now suppose user does a mass Update and changed the status of the 250 opportunities to ‘Closed Won’, as per trigger functionality the first 200 records will be processed in the first batch and Trigger.New context variable will contain these 200 opportunity records to be iterated, now if you go via the faulty code and write the DML statement Line 12 (insert tsk) inside the loop it would amount to 200 DML statements which is against the Governor limit defined in the above table and the operation would fail.
Now to take care of these Governor limits we make use of collections and always make sure that we do not write any DML statements inside our loops. This is known as Code Bulkification. So instead of writing the DML statement inside for loop we added all the tasks in a List, using the add function and insert all the tasks using a Single DML statement on Line 18(below Image). Hence the use of collections is of upmost importance.
Line 11: – There is a reason for using after Triggers in this case, since the Id of the Opportunity wouldn’t be available in before events and expression “WhatId = opp.Id” would not make any sense.
WhatId will associate the task to the opportunity, if you open any task record, you will see a field named ‘Related To’ and the API name of this field is ‘WhatId’.
Important Note: –
- We always use the API name of the fields when we are coding in APEX.
- Always write only one trigger per object, since we won’t be able to control the Order of execution if multiple triggers are involved for a single object.
- Your code should always be bulkified to handle more than one record at a time and not to hit the Governor limits specified by Salesforce.
At Last now we’ll test our second trigger, create any new opportunity and make the status as ‘Closed Won’ or Edit any existing opportunity and change the Stage to ‘Closed Won’ and Save the Record. On successful save in Open Activities section, you’ll see a new task record created.
ORDER OF EXECUTION
Bonus Section: – This is part of the bonus section where we’ll see the Order of Execution of Salesforce, i.e. series of events occurring once you click the save button. This will give you a clear picture of what happens behind the scene as you click save button on the screen.
When a user clicks on save while inserting/editing any record the order of execution of events occurring till the record is saved to the database is as follow.
- System Validations run (Checking the Datatype, Format, Unique, Required).
- Before Triggers (we have already seen this, it’s used to populate field values in the same object record).
- Custom + System validations run
- Duplicate rules (out of the box duplicate rules configured in your Org run now).
- The Record is saved to the Database, but not committed, this is where Record Id is generated.
- After Trigger runs.
- Workflow rule runs (If there are any workflow configured to run on Insert/Update meeting the required conditions if any), and if there is any field update it is followed by: –
System Validation -> Before Triggers -> Save -> After Triggers.
- Process Builder runs (If there are any PB configured to run on Insert/Update meeting the required conditions if any), and if there is any field update it is followed by: –
System Validation -> Before Triggers -> Save -> After Triggers
- Roll Up Summary
- Criteria Based Sharing Rules.
- Database Commit.
We will Cover SOQL in some other Blog post, it’s the Shield of the Achilles, if you master it, you can almost do anything when you code in Apex.