Insycle Blog

Apex Triggers in Salesforce — A Simple Guide

Written by Ryan Bozeman | Jan 29, 2021 6:02:22 PM

 

As companies begin to expand the number of ways in which they use Salesforce within their organization, they look for more in-depth and automated ways to take care of specific tasks in the system. And ever-expanding reliance on Salesforce means that manual tasks can become a huge slow down across your organization.

Apex triggers within Salesforce are designed to help you automate certain tasks. Apex triggers allow you to perform custom actions before and after events in Salesforce. These events can include things such as data insertions, updates to existing data, or deletions.

Let's take a look at what Apex triggers are in Salesforce, how they are typically used, and why they may be a benefit to your organization.

What are Apex Triggers in Salesforce?

A Salesforce trigger is an apex script that executes either before or after a data manipulation language (DML) event occurs. Some examples of what data manipulation language events include are actions like inserting new records into a database, deleting records from a database, updating records within your sales force, or generally manipulating data through the system.

Apex triggers allow you to perform tasks that are not possible using the point-and-click tools in the Salesforce user interface.

Apex triggers are designed to allow you to perform custom actions either before or after the data manipulation language event takes place. Apex scripts are written in the Apex language, triggered either before or after the data manipulation takes place.

There are two different types of Apex triggers within Salesforce:

  • “Before” Apex Triggers. These are used to update or validate the value in a record before you save it to your Salesforce database.
  • “After” Apex Triggers. These are used to access the values contained within a record and use that value to make changes to other records in your Salesforce database. Unlike “Before” triggers, “After” triggers are read-only.

Both types of triggers are useful for managing records and executing additional actions after manipulating data within your Salesforce database.

Here is what an Apex Trigger script looks like:

Trigger trigger Name on sObject(Trigger event)

{

//logic

}

That is a default setting. They are able to process multiple different records simultaneously. Both triggers can handle single or book operations including data Imports, bulk API calls, and bulk actions.

Apex triggers can be executed after a number of different actions are taken within the Salesforce system including:

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

Triggers can be defined for any top-level standard objects including accounts, contacts, and custom objects. Those triggers are activated by default when created.

Where is Apex Trigger Code Written in Salesforce?

If you’ve never used Apex Triggers in the past, figuring out where to place the actual triggers within the Salesforce system can be a bit confusing.

Additionally, you don’t want to start by launching codes to your live system. If it is your first time using Apex Triggers, you’ll want to run some tests before deploying anything live.

There are two places where you can practice writing Apex Trigger codes in Salesforce without the changes affecting your live database:

  1. Sandbox – A vast majority of people code their triggers here. Sandboxes are developer-friendly copies of your normal org and can be created at any time.
  2. Developer Edition – A perfect place to practice if you don’t want to use sandboxes.

No matter what version you are using — your live Salesforce database, a sandbox, or the Developer Edition — you can access the “Triggers” section by navigating to:

Setup >> Custom Code >> Apex Triggers

Here you can view all of your existing Apex Triggers, but cannot create new triggers.

 

You can find the Triggers for specific object types under the Object Manager menu. You can also delete Triggers from the Salesforce user interface. For example, here is what navigating to the Apex Triggers for the Account object looks like in the Salesforce user interface:

 

 

Related articles

How to Merge Accounts in Salesforce Flexibly and Automatically

4 Best Practices for Salesforce Data Cleansing

Salesforce and ABM - Associating Leads and Contacts to Accounts

 

Salesforce Apex Trigger Example

Let’s look at some examples of different types of Apex Triggers, to give you an idea of how they can be used. This is a simple example, meant to provide an easily understood overview of what is possible through Salesforce triggers.

Apex Trigger Example #1: HelloWorld

In the Developer Console, click “File > New > Apex Trigger.”

Name the trigger “HelloWorldTrigger” and choose “Account” as the sObject.

The developer console will show the default code that all Apex Triggers show before you make changes. Instead, enter the following Apex Trigger script:

trigger HelloWorldTrigger on Account (before insert) {

        System.debug('Hello World!');

}

Then you can save it.

To test if the script is working, create a new account.

You can also add the account manually through the debug system. When complete, you should see “Hello World!” in the debug window.

Let’s take a look at some more real-world applications for Apex Triggers.

Apex Trigger Example #2: Mark Accounts in Specific Industries as ‘Hot’

Your business probably prioritizes accounts and prospects in certain industries. It makes sense. Industries that are growing or are a particularly good fit for your offer should receive more attention from your internal teams.

But often, that means that someone at your organization has to keep an eye on new accounts to mark them appropriately in Salesforce.

This can be done automatically using Apex triggers.

In the example below, we show how you can use Apex Triggers to mark new accounts that are from the technology or finance industries as “hot” in the system, helping your sales team to prioritize those accounts.

trigger AccountRatingTrigger on Account (before insert, before update) {

  for(Account account : Trigger.New) {

    if (account.Industry != null &&

               (account.Industry == 'Technology' || account.Industry == 'Finance')){

       account.Rating = 'Hot';

    }

  }

}

This is a great example of a simple and effective way to identify priority accounts for salespeople within your Salesforce database.

Trigger Context Variables

Here is a complete list of all of the Apex Trigger context variables that can be utilized in Salesforce.

Variable

Usage

isExecuting

Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.

isInsert

Returns true if this trigger was fired due to an insert operation

isUpdate

Returns true if this trigger was fired due to an update operation

isDelete

Returns true if this trigger was fired due to a delete operation.

isBefore

Returns true if this trigger was fired before any record was saved.

isAfter

Returns true if this trigger was fired after all records were saved.

isUndelete

If a record is recovered from the recycle bin it returns trigger true.

new

Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers.

newMap

A map of IDs to the new versions of the sObject records.

old

Returns a list of the old versions of the sObject records.

oldMap

A map of IDs to the old versions of the sObject records.

size

The total number of records in a trigger invocation, both old and new.

Salesforce Apex Triggers — Beyond the Basics

Apex Triggers can be a powerful tool for companies to automate complex processes that otherwise would have to be handled manually, making it a vital tool for data management practices.

Let’s dive a bit deeper and look at some of the more advanced considerations for Apex Triggers:

Apex Trigger Best Practices

Using Apex Triggers becomes a whole lot easier if you follow a few simple best practices. In following these, you can help to cut down on the learning curve and avoid mistakes that are common among new apex trigger users.

Best Practice #1: Bulkify Your Code

Bulkifying Apex code ensures that the code that you are running is able to effectively handle more than a single record at once. When a collection of records initiates Apex, a single instance of that code is executed. Still, that Apex Trigger code needs to be able to handle all of the records that were a part of that collection.

Best Practice #2: Avoid SOQL Queries or DML statements inside FOR Loops

A common mistake with Apex Triggers is having queries or DML statements that are placed within a “for” loop. This causes issues because there is a governor limit that enforces a maximum number of SOQL queries. Additionally, there is another governor limit that affects the number of DML statements — including inserts, updates, deletes, and undeletes.

These statements should be outside of loops. 

Best Practice #3: Bulkify Helper Methods

Like our previous best practices, Helper Methods need to be able to run in a bulk manner and not execute within an iteration or a “for” loop. These actions increase the risk that you will go beyond the governor limit.

This APEX best practices article explains in more depth, providing examples of how to use SOQL and DML statements correctly and incorrectly. 

Triggers and Callouts for Integration with Third-Party Apps

Apex allows you to make callouts to integrate Apex code with third-party apps. For example, you could make a callout to a third-party data provider to update records within Salesforce.

When you make a callout from an Apex trigger in Salesforce, the callout should typically not block other actions while waiting for the external service’s response. Apex callout limits and limitations ensure that a transaction is not held open for a potentially long period of time, in order to avoid locking the records.

Triggers can also be used to build upon Salesforce's robust validation rules and create your own customer validation rules.

To make a callout, call a class method that executes asynchronously. These methods are called future methods and are annotated with “@future(callout=true).

Apex Triggers Can Be a Key Tool for Data Management in Salesforce

Apex Triggers make a natural complement to Insycle for any company that is looking to improve their data management operations and data management workflows. Apex triggers can help you to avoid costly data-related mistakes inside of Salesforce while streamlining and automating actions that otherwise would have had to be performed manually.

Apex triggers help you to manage how specific types of data are handled internally, helping you to execute a broader overall data maintenance and management strategy. With Apex triggers and Insycle paired, you can effectively identify, handle, and fix common data management issues — such as merging duplicate accounts, standardizing job titles, and formatting address and phone number fields consistently.

Insycle is a complete data management platform for Salesforce. Insycle can help you to take control of your data management processes and deduplicate, cleanse, and standardize your data in bulk, and automatically at set intervals.

Learn more about ways to put your Salesforce data maintenance on autopilot and improve data quality in your CRM.