SaasGuru Logo

🎉Supercharge Your Salesforce Career with 18+ Certifications, 50+ Labs & Mock Exams. Start your FREE Trial now! 🎉

🎉Supercharge Your Salesforce Career with 18+ Certifications, 50+ Labs & Mock Exams. Start your FREE Trial now! 🎉
Triggers in Salesforce - An Ultimate Guide

Apex Triggers in Salesforce: Types, Syntax and How-To Create

Salesforce offers an ample amount of career opportunities as the requirements of Salesforce services steadily grow with the size of an organization.

When any business grows, complexity increases in daily operations. In that case, the demand for efficient automation becomes the need of the hour for complex tasks in the organization.

It can slow down all business processes if organizations keep using existing Salesforce services without automation. Manual operation does the job for smaller tasks, but when businesses grow bigger, processes and tasks tend to become more complex. To handle that, it is advisable to have automation in place.

This is where the Apex Triggers in Salesforce come into play. Apex Triggers help automate complex tasks in Salesforce.

Apex Triggers are specifically designed to perform a complex series of actions in Salesforce, after and before some events like when a record is created, updated, or deleted. It turns out to be effective in data management as well.

As Triggers make many tasks easy, it is important for you to know about them and how they work. In this post, we will explore in detail how exactly Apex Triggers help businesses achieve the required degree of automation.

What is Apex Triggers?

Apex Triggers help you perform custom actions before or after specific operations on Salesforce records, like when a record is created, updated, or deleted.

The triggers are apex codes that execute before or after specific operations, include;

  • insert
  • update
  • delete
  • merge
  • upsert
  • undelete

You can update records of the same object or multiple objects at once with Triggers. As there are different types of actions in operation, Triggers need to be different for that particular action. So, there are different types of Salesforce Triggers for that. Let’s learn what they are.

Become a Salesforce Certified Professional

What are the Different Types of Apex Triggers in Salesforce?

Broadly, there are 2 types of Triggers in Salesforce.

  • Before Triggers
  • After Triggers

Before Triggers help you update and validate values in a  record before committing it to the database. 

On the other hand, After Triggers help to fetch the values in the records. With After Trigger, you can utilize those values to make changes in other records. 

One more difference between the two is you can edit and update records with the help of before Triggers, but After Triggers are read-only.

Read about What are Apex Methods?

Syntax of Trigger

Syntax of Trigger

Here, you can give a name to your Apex Trigger in the Trigger name. In the object name, select any action that you intend to execute. And in the Trigger event, you can select any event from multiple options.

    • Before update: Executes the trigger before a record is updated
    • Before insert: Executes the trigger before a record is inserted
    • Before delete: Executes the trigger before a record is deleted
    • After delete: Executes the trigger after a record is deleted
    • After insert: Executes the trigger after a record is inserted
    • After update: Executes the trigger after a record is updated
    • After undelete: Executes the trigger to recover a deleted record from recycle bin

How to Create an Apex Trigger in Salesforce?

If you have never created Triggers before, it can be a bit confusing in which system you can create them, production or sandbox. Moreover, you would never want to experiment with creating Triggers in a production environment. You should use some test simulations before the actual creation and execution of the trigger in the live system.

A sandbox or a developer edition org is your go-to place to play around with triggers. No matter what apex code you run there, it doesn’t affect your live Salesforce database.

  • Sandbox is very convenient for developers. That’s why the majority of them prefer to spin a developer sandbox to code the Triggers in quickly. 
  • If you do not want to use a sandbox, then a developer edition is your best friend to help you practice.

Let’s create a simple trigger on the Account object. Follow the below steps to create a trigger:

creating new apex trigger

  1. Click the “Setup” icon.
  2. Right-click on the “Developer Console” and click “Open link in New Tab.” This way, the developer console opens as a tab in the browser window rather than a new window. This is more convenient to work with.
  3.  Click “File” -> “New” -> “Apex Trigger”
  4. Specify “Name” and select “Object.”
  5. Click “Submit.” 

new apex trigger

6. Then, you will see the syntax that we talked about earlier in this post. Now start writing your Apex Trigger. You will find the default code in the Apex Trigger. Replace that code with the following code.

trigger AccountTrigger on Account (before insert) {System.debug(‘Welcome’);}

trigger syntax

7. Now, create an Account and check if the trigger is working or not. If it creates an account, then the trigger is working. You will find welcome in the debug window when it is completed.

Once you have created some triggers, where do you find them? Here are the steps that you can follow:

  1. Navigate to set up
  2. Type “apex triggers” in the quick find box and click “Apex Triggers” under the Custom code section.
  3. The apex Triggers page will open in setup showing you the list of Triggers created so far or the ones that are part of a managed package.

apex triggers - setup

Triggers are generally used to execute actions that are not possible to perform with point-and-click tools in Salesforce. Let’s try to understand creating trigger with an example,

What are Trigger Exceptions?

Trigger exceptions are the restrictions that you sometimes need in the database operation. Trigger exceptions are also called Block Triggers. For example, Triggers can be used to prevent the occurrence of DML operations by using the addError() method on the field.

So when Triggers are used, custom error messages will be seen in the application interface. There is a minimum delay in response time if errors are added before the Triggers.

Triggers vs. Workflow in Salesforce

Triggers and Workflows are both automation tools in Salesforce. Triggers are programmatic, and Workflows are declarative in nature. So let’s not get confused between the two. Here are four major differences between an Apex Trigger and a Workflow Rule.

Apex Triggers

Salesforce Trigger & Revenue Box

How can you get the maximum out of Salesforce Trigger with the Help of Revenue Box?

You can combine the Salesforce Trigger and Revenue Box to resolve some common data management issues in the Salesforce Inbox and Einstein activity capture (EAC).

As of now, you are aware that Triggers can automate complex tasks in your database and workflow. You can do the same with your incoming and outgoing emails with the help of the Triggers.

EAC in Salesforce helps auto-log your emails from Gmail and Outlook to your Salesforce. But EAC and Apex email task Triggers do not work together. Because EAC does not store physical records of the captured emails from Gmail or Outlook, they only show virtual activities and timelines on the record but are not stored physically.

This is the reason they are not considered a core Salesforce activity, so Triggers do not work for them. Hence you are unable to update Contacts in your database from your recent emails. This is where the Revenue Box helps you solve this problem.

Revenue Box works the same as Salesforce Inbox, but apart from that, it stores emails that enable you to create Triggers. Moreover, the Revenue Box can automate the data capture from the emails and facilitates active synchronization between Salesforce and email services like Outlook and Gmail.

Salesforce Apex Triggers: Applications

To enhance our understanding of Salesforce Triggers, let’s delve into some practical aspects of working with Triggers. This includes writing Triggers, using context variables, calling class methods from a trigger, adding related records, and making trigger callouts.

Writing Triggers

Writing triggers involves creating an Apex script that runs before or after a specific data manipulation language (DML) event occurs, such as a record being inserted, updated, or deleted.The basic syntax for writing a trigger includes the trigger name, the object it operates on, and the DML events it responds to. Then, within the trigger, you write Apex code that performs the necessary actions. Remember, a trigger definition is surrounded by curly braces {} and each code statement within the trigger is ended with a semicolon (;).

Trigger Example

Here’s an example of a simple Apex Trigger that is fired before a record is inserted into the ‘Account’ object:

trigger AccountTrigger on Account (before insert) {

    for(Account a : Trigger.new) {

        // Write the logic here

    }

}

This trigger loops through each new account record being inserted (denoted by ‘Trigger.new’) and performs whatever logic you have written inside the loop.

  1. Using Context Variable: Context variables in Salesforce are predefined variables that provide access to the runtime context in which the trigger is executing. They include Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap, and more. For example, Trigger.new contains all the records that were inserted in insert and update triggers.
  2. Calling a Class Method from Trigger: Triggers should be kept lean, meaning they should only contain logic to determine when to execute. The actual execution should be carried out by class methods. Here is an example of how to call a class method from a trigger:

Trigger Account

Trigger on Account (before insert) {

    AccountTriggerHandler handler = new AccountTriggerHandler();

    handler.onBeforeInsert(Trigger.new);

}

In the above example, the ‘AccountTriggerHandler’ is a class that contains the method ‘onBeforeInsert’ which executes the required logic.

  1. Adding Related Records: Triggers can also be used to create or modify related records. For example, a trigger on the Account object could create a new Contact record whenever a new Account is inserted.
  2. Trigger Callouts: Triggers can make callouts to external services. However, since you can’t make a synchronous callout (one that waits for a response) from a trigger, you would use an @future method in a class to make an asynchronous callout.

Incorporating practical elements into our understanding of Triggers allows us to better grasp their application. For a more detailed explanation, you can watch this YouTube video which provides an excellent tutorial on working with Salesforce Triggers.

Get your Salesforce Certifications on the first go

Recursive Trigger and Bulkifying Trigger

A Recursive Trigger is an event where the same Trigger is fired again due to the results generated by the trigger and creates an infinite loop. A Recursive Trigger must be avoided at any cost. If such an unfortunate event happens, then you will hit the Salesforce governor limits. To avoid a recursive trigger, you need to create a static variable and keep checking the value of that variable before any execution in the trigger.

The basic purpose of a trigger is to handle multiple records that can be hundreds or thousands. All those need to be handled efficiently. In this case, you can bulkify the Triggers.

To bulkify the Trigger, you should write a Trigger that can facilitate efficient DML and SOQL operations. Data operations may hit the upper limit if you do not perform this action. So, it is always a best practice to bulkify your triggers.

So, that’s it about Salesforce Triggers. We hope you have received so many insights and the applicability of Salesforce Triggers. If you still have any queries, do not hesitate to connect with us. We will be delighted to assist you.

Sign Up now to get information about more Salesforce features and concepts.

Get certified as a Salesforce Developer in your first attempt with saasguru by enrolling in our Salesforce Platform Developer 1 training program.

You can also check out our Salesforce Developer Course: PD 1 Certification.

Frequently Asked Questions (FAQs)

1. What are triggers in Salesforce?

Triggers in Salesforce are programmatic event handler that executes custom actions before or after specific operations on Salesforce records. These operations can include the creation, update, or deletion of a record. Triggers, written in Apex (Salesforce’s proprietary programming language), provide a powerful way to automate complex business processes.

2. What is the use of triggers in Salesforce?

The primary use of triggers in Salesforce is to automate and manage complex business operations that can’t be handled by Salesforce’s built-in point-and-click tools. Triggers can validate or modify field values before they’re saved to the database, create or modify related records, perform complex calculations, enforce custom business logic, or integrate with external systems.

3. How many types of triggers are there in Salesforce?

There are two main types of triggers in Salesforce:

  • Before Triggers: These are used to update or validate record values before they’re saved to the database. They are useful for enforcing business rules and data integrity.
  • After Triggers: These are used to access field values that are set by the system and to affect changes in other records. After triggers are typically read-only.

4. When to use triggers in Salesforce?

Triggers in Salesforce should be used when complex business processes or custom logic need to be implemented that cannot be achieved using Salesforce’s declarative (point-and-click) tools, such as Process Builder or Flow. Scenarios where you might need to use triggers, include validating record data before it’s saved, manipulating the value of a field based on changes in other fields, or creating or updating related records based on the creation, update, or deletion of a record.

5. What are the best practices for triggers in Salesforce?

Here are a few best practices for triggers in Salesforce:

  • Bulkify your Code: Always write triggers that can handle multiple records at a time to respect Salesforce’s governor limits.
  • Avoid Recursive Triggers: Ensure your trigger doesn’t re-fire itself, leading to an infinite loop.
  • One Trigger per Object: To keep better control of the order of operations, it’s recommended to have only one trigger per object.
  • Keep Business Logic in Helper Classes: Instead of writing all the business logic inside the trigger, write the logic in a separate class and call this class from the trigger.
  • Test Coverage: Always aim for a minimum of 75% test coverage to ensure the trigger works as expected.
  • Error Handling: Include proper error handling to display meaningful error messages to the end user.

Remember, triggers should be your last resort. Always try to achieve functionality using declarative tools before resorting to triggers.

6. How do I avoid trigger errors in Salesforce?

Trigger errors in Salesforce can be avoided by following some of the below practices:

  • Bulkify Your Code: Make sure your triggers are capable of handling multiple records at once. Without this, you may hit governor limits when processing large sets of data.
  • Avoid Recursive Triggers: A recursive trigger is an event where the same trigger is fired repeatedly, leading to an infinite loop. Create a static variable and check its value before any execution in the trigger to prevent this.
  • Exception Handling: Include exception-handling logic in your triggers to handle unexpected issues gracefully.
  • Proper Testing: Ensure to cover all scenarios, both expected and unexpected, during the testing phase. Salesforce recommends at least 75% code coverage for the triggers.

7. How do I debug triggers in Salesforce?

Debugging triggers in Salesforce can be done using debug logs. These logs will provide information about the execution path, performance issues, exceptions, and database changes.

  • From Salesforce’s Setup, enter “Debug Logs” in the Quick Find box and select Debug Logs.
  • Click “New” to create a new debug log.
  • Choose the user you want to monitor, set the debug level (which includes the log levels for Apex Code and System), and save.
  • Now perform the operation that fires the trigger. The debug log will be generated.

You can then analyze the log to find any issues or errors.

8. How do I query triggers in Salesforce?

Salesforce doesn’t support directly querying triggers from the database like it does with custom objects or records. Triggers are metadata, and to retrieve metadata, the Metadata API or tools like Workbench, which use this API, are typically used.

However, you can query the ApexTrigger object to get information about triggers. For example, SELECT Id, Name FROM ApexTrigger will provide the IDs and names of all Apex Triggers.

9. What are the limitations of triggers in Salesforce?

There are several limitations of triggers in Salesforce:

  • Governor Limits: Salesforce enforces various limits on the number of database operations, the amount of CPU time, and the memory capacity that triggers can use.
  • Order of Execution: The order in which triggers are executed can’t be explicitly controlled.
  • Testing and Deployment: Triggers must have at least 75% test coverage in order to be deployed to a production environment.
  • Recursive Triggers: Avoiding recursive triggers can be complex. If the same trigger is fired continuously, you may run into infinite loops.
  • Complexity: Triggers can become complex, especially as more business logic is added. This can lead to difficult-to-maintain code.
Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unsure of Your Next Step?

Take our quick 60-second assessment to discover the Salesforce career path or learning journey that’s a perfect fit for you.

Related Articles

Salesforce Data Cloud Vs. Customer Data Platform (CDP)

Struggling to choose between Salesforce Data Cloud and a CDP? Learn their strengths, use cases, and key considerations to help you pick the perfect tool.

Salesforce Introduces AI Implementation and Data Governance Bundles

Explore Salesforce’s new AI Implementation and Data Governance bundles designed for secure and efficient AI rollouts. Read now!

Humans of Salesforce – Rupam Patra

Explore Rupam Patra’s journey from a curious student to a Salesforce Trailblazer and get top tips for your own Salesforce career. Read now!