Concept of Apex Triggers

Last updated on Nov 24 2021
Abha Kulkarni

Table of Contents

Concept of Apex Triggers

Apex triggers are like stored procedures which execute when a specific event occurs. A trigger executes before and after an occasion occurs on record.
Syntax

trigger triggerName on ObjectName (trigger_events) { Trigger_code_block }

Executing the Trigger
Following are the events on which we will fir the trigger −
• insert
• update
• delete
• merge
• upsert
• undelete
Trigger Example 1
Suppose we received a business requirement that we’d like to make an Invoice Record when Customer’s ‘Customer Status’ field changes to Active from Inactive. For this, we’ll create a trigger on APEX_Customer__c object by following these steps −
Step 1 − attend sObject
Step 2 − Click on Customer
Step 3 − Click on ‘New’ button within the Trigger related list and add the trigger code as give below.

// Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List InvoiceList = new List();

for (APEX_Customer__c objCustomer: Trigger.new) {

if (objCustomer.APEX_Customer_Status__c == 'Active') {
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}

// DML to insert the Invoice List in SFDC
insert InvoiceList;
}

Explanation
Trigger.new − this is often the context variable which stores the records currently within the trigger context, either being inserted or updated. during this case, this variable has Customer object’s records which are updated.
There are other context variables which are available within the context – trigger.old, trigger.newMap, trigger.OldMap.
Trigger Example 2
The above trigger will execute when there’s an update operation on the Customer records. Suppose, the invoice record must be inserted only the Customer Status changes from Inactive to Active and not every time; for this, we will use another context variable trigger.oldMap which can store the key as record id and therefore the value as old record values.

// Modified Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List InvoiceList = new List();

for (APEX_Customer__c objCustomer: Trigger.new) {

// condition to see the old value and new value
if (objCustomer.APEX_Customer_Status__c == 'Active' &&

trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}

// DML to insert the Invoice List in SFDC
insert InvoiceList;
}

Explanation
We have used the Trigger.oldMap variable which as explained earlier, may be a context variable which stores the Id and old value of records which are being updated.

Apex – Trigger Design Patterns

Design patterns are wont to make our code more efficient and to avoid hitting the governor limits. Often developers can write inefficient code which will cause repeated instantiation of objects. this will end in inefficient, poorly performing code, and potentially the breaching of governor limits. This most ordinarily occurs in triggers, as they will operate against a group of records.
We will see some important design pattern strategies in this blog.
Bulk Triggers Design Patterns
In real business case, it’ll be possible that you simply may have to process thousands of records in one go. If your trigger isn’t designed to handle such situations, then it’s going to fail while processing the records. There are some best practices which you would like to follow while implementing the triggers. All triggers are bulk triggers by default, and may process multiple records at a time. you ought to always decide to process quite one record at a time.
Consider a business case, wherein, you would like to process sizable amount of records and you’ve got written the trigger as given below. this is often an equivalent example which we had taken for inserting the invoice record when the Customer Status changes from Inactive to Active.

// Bad Trigger Example
trigger Customer_After_Insert on APEX_Customer__c (after update) {

for (APEX_Customer__c objCustomer: Trigger.new) {

if (objCustomer.APEX_Customer_Status__c == 'Active' && 
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {

// condition to see the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
insert objInvoice; //DML to insert the Invoice List in SFDC
}
}
}

You can now see that the DML Statement has been written certain the loop block which can work when processing only few records but once you are processing some many records, it’ll reach the DML Statement limit per transaction which is that the governor limit. we’ll have an in depth look on Governor Limits during a subsequent chapter.
To avoid this, we’ve to form the trigger efficient for processing multiple records at a time.
The following example will assist you understand an equivalent −

// Modified Trigger Code-Bulk Trigger
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List InvoiceList = new List();

for (APEX_Customer__c objCustomer: Trigger.new) {

if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {

//condition to see the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);//Adding records to List
}
}

insert InvoiceList;
// DML to insert the Invoice List in SFDC, this list contains the all records 
// which require to be modified and can fire just one DML
}

This trigger will only fire 1 DML statement because it are going to be operating over an inventory and therefore the List has all the records which require to be modified.
By this manner , you’ll avoid the DML statement governor limits.

Trigger Helper Class

Writing the entire code in trigger is additionally not an honest practice. Hence you ought to call the Apex class and delegate the processing from Trigger to Apex class as shown below. Trigger Helper class is that the class which does all the processing for trigger.
Let us consider our invoice record creation example again.

// Below is that the Trigger without Helper class
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List InvoiceList = new List();

for (APEX_Customer__c objCustomer: Trigger.new) {

if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {

// condition to see the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}

insert InvoiceList; // DML to insert the Invoice List in SFDC
}

// Below is that the trigger with helper class
// Trigger with Helper Class
trigger Customer_After_Insert on APEX_Customer__c (after update) {
CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap);
// Trigger calls the helper class and doesn't have any code in Trigger
}

Helper Class

public class CustomerTriggerHelper {
public static void createInvoiceRecords (List

customerList, Map oldMapCustomer) {
List InvoiceList = new Listvapex_invoice__c>();

for (APEX_Customer__c objCustomer: customerList) {

if (objCustomer.APEX_Customer_Status__c == 'Active' &&
oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {

// condition to see the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();

// objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}

insert InvoiceList; // DML to insert the Invoice List in SFDC
}
}

In this, all the processing has been delegated to the helper class and once we need a replacement functionality we will simply add the code to the helper class without modifying the trigger.

Single Trigger on Each Object

Always create one trigger on each object. Multiple triggers on an equivalent object can cause the conflict and errors if it reaches the governor limits.
You can use the context variable to call the various methods from helper class as per the need . Consider our previous example. Suppose that our createInvoice method should be called only the record is updated and on multiple events. Then we will control the execution as below −

// Trigger with Context variable for controlling the calling flow
trigger Customer_After_Insert on APEX_Customer__c (after update, after insert) {

if (trigger.isAfter && trigger.isUpdate) {
// This condition will check for trigger events using isAfter and isUpdate
// context variable
CustomerTriggerHelper.createInvoiceRecords(Trigger.new);

// Trigger calls the helper class and doesn't have any code in Trigger
// and this may be called only trigger ids after update
}
}

// Helper Class
public class CustomerTriggerHelper {

//Method to make Invoice Records
public static void createInvoiceRecords (List customerList) {

for (APEX_Customer__c objCustomer: customerList) {

if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {

// condition to see the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}

insert InvoiceList; // DML to insert the Invoice List in SFDC
}
}

 

So, this brings us to the end of blog. This Tecklearn ‘Concept of Apex Triggers’ blog helps you with commonly asked questions if you are looking out for a job in Salesforce. If you wish to learn Salesforce and build a career in Salesforce domain, then check out our interactive, Salesforce Certification Training: Admin 201 and App Builder, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Salesforce Certification Training: Admin 201 and App Builder

Salesforce Certification Training: Admin 201 and App Builder

About the Course

Salesforce Certification Training course will help you pass the Salesforce Administrator Exam (Admin 201) and the Salesforce App Builder (Dev 401) Exam. Concepts on Force.com Platform, AppExchange, SFDC Security Model, Service Cloud, Sales Cloud, Lightning App Builder, Salesforce Reports & Dashboard can be mastered in this Salesforce Training course. You can also configure the platform, manage users, find better ways to use the platform’s features, build applications with Salesforce Lightning, and more. Further, in this Salesforce certification training course, you will master App builder, Apex, Visualforce, etc.

Why Should you take Salesforce Admin 201 and App Builder Training?

• As per Indeed.com data, 200% global jump in Salesforce jobs since Jan 2016. Salesforce Certified Administrators earn an annual average salary of $87,000 but can go as high as $160,000 depending on their knowledge, skills, and experience.
• More than 200,000 companies worldwide use Salesforce platform. Salesforce leads the CRM market with 19.5 percent of market share – Forbes.
• The global CRM software market will reach US$40.26 billion in 2023, up from US$36.9 billion (2020) – Statista.

What you will Learn in this Course?

Salesforce Fundamentals
• Introduction to CRM concepts and Cloud computing
• Salesforce.com Overview and Fundamentals
• Understanding Salesforce Platform
Understanding Salesforce Platform
• Understanding Salesforce Terminologies and Introducing the force.com platform
• Understanding Salesforce Metadata and API
• Describe the capabilities of the core CRM objects in the Salesforce schema
• Identify common scenarios for extending an org using the AppExchange
• About Salesforce Certification
Introduction to Sales Cloud
• Sales Cloud
• Sales Process
• Sales Productivity Features
• Lead Management
• Lead auto response
• Lead assignment
• Web to lead
• Accounts and Contacts Management
• Opportunities
• Campaign Management
Security Model, User Management and Its Features
• Security Model Mind Map
• System Level or Org Level Security
• User Administration and Troubleshooting
• Permission Sets
• Profile Management
• User Actions
• Assigning Permission
• Session settings
• Activations
• Page layout assignment
• Tab setting
• Field level security
Object, Record and Field Level Features
• Custom Object
• Custom Field
• Data Types
• Relationship among Objects
• Working with App and Tabs
Data Handling and Processing
• Data Import and Export with Salesforce
• Insert, Update and Delete Data with Salesforce
• Export Data with UI
• Export Data using Data Loader Tool
Deployment
• SandBox
• Moving Data from SB to Production – Deployment
• Types of SandBox
• Change Sets
• Types of Change Sets
Application Cycle
• Milestones
• Sandboxes
• Change Sets
• Packages
Reports and Dashboards
Declarative Implementation in Salesforce
Salesforce Development and Apex Programming
• Apex Programming
• Apex Classes
• Apex Settings
• SOQL – Salesforce Object Query Language
• DML Commands
• Apex Class in Detail
• Apex Triggers
• Apex Testing
• Access Specifier in Salesforce
• Testing
Lightning in Salesforce
• Lightning Components
• Lightning Component Capabilities
• Lightning Components vs. Visualforce
Visual Force in Salesforce
• Standard Visualforce controller and controller extensions,
• Visualforce Page
• Understanding the MVC Pattern
• Tools for Visualforce Development
• Visual Force Components
WorkFlows in Salesforce
• Work Flows in Salesforce
• Types of Work Flows
• Work Flows Rules
About Preparation of Salesforce 201 and App Builder Certification exams

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Concept of Apex Triggers"

Leave a Message

Your email address will not be published. Required fields are marked *