SaasGuru Logo

Kickstart your career with the World's First Salesforce & AI Programs by an IIT - Explore Courses 🎉

Kickstart your career with the World's First Salesforce & AI Programs by an IIT - Explore Courses 🎉
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

Best Practices for Writing Efficient Apex Triggers

Apex Triggers are a powerful tool in Salesforce, enabling complex automation and business logic. To ensure optimal performance and maintainability, it is crucial to follow best practices when writing Apex Triggers. Here are some essential best practices:

  1. Bulkify Your Code: Always design Apex Triggers to handle multiple records at once. Bulkifying your code ensures that it operates within Salesforce’s governor limits, making it efficient and scalable. Use collections like lists or maps to process records in bulk, rather than operating on a single record at a time.
  2. Use Context Variables: Leverage context variables such as Trigger.new, Trigger.old, Trigger.newMap, and Trigger.oldMap to access and manipulate records efficiently within your trigger. These variables help you understand the state of the records and perform the necessary operations accordingly.
  3. One Trigger Per Object: Maintain only one trigger per object to avoid conflicts and ensure a clear execution order. This practice simplifies debugging and enhances code readability. You can manage multiple actions within a single trigger by using helper classes or handler frameworks.
  4. Avoid Hardcoding IDs: Instead of hardcoding IDs, use custom settings or custom metadata types to store configurable data. This approach makes your code more flexible, easier to maintain, and adaptable to different environments.
  5. Keep Logic in Helper Classes: To keep your triggers clean and focused, move complex business logic to helper classes. The trigger should primarily handle the execution flow, while the helper classes contain the detailed logic. This separation of concerns improves code organization and reusability.
  6. Implement Error Handling: Ensure robust error handling within your triggers to manage exceptions gracefully. Use try-catch blocks to capture and handle errors, and provide meaningful error messages to users or administrators. Proper error handling helps maintain data integrity and improves user experience.
  7. Test Coverage: Aim for at least 75% test coverage for your Apex Triggers to ensure they work as expected in all scenarios. Write comprehensive test cases that cover both positive and negative scenarios, and include bulk operations to validate the trigger’s behavior under different conditions.
  8. Prevent Recursive Triggers: Recursive triggers can lead to infinite loops and exceed governor limits. Implement static variables to track the execution state and prevent re-triggering within the same transaction. This practice helps maintain system stability and performance.

By following these best practices, you can write efficient Apex Triggers that enhance Salesforce automation, maintain system performance, and ensure scalability.

Advanced Use Cases for Apex Triggers

Apex Triggers in Salesforce offer powerful automation capabilities that can handle complex business logic beyond what declarative tools provide. Here are some advanced use cases for Apex Triggers that can significantly enhance your Salesforce implementations:

Implementing Complex Business Logic

Apex Triggers are ideal for implementing complex business rules that require custom logic. For example, you can automatically assign high-value opportunities to a senior sales team member based on specific criteria.

Example:

trigger OpportunityAssignment on Opportunity (before insert) {
for (Opportunity opp : Trigger.new) {
if (opp.Amount > 100000) {
opp.OwnerId = ‘005XXXXXXXXXXXX’; // Assign to a specific user
}
}
}

Automating Data Management

Apex Triggers can streamline data management processes by automatically updating related records. For instance, when an Account record is updated, a trigger can ensure that all associated Contact records are also updated accordingly.

Example:

trigger UpdateContactRecords on Account (after update) {
List<Contact> contactsToUpdate = new List<Contact>();
for (Account acc : Trigger.new) {
for (Contact con : [SELECT Id, AccountId FROM Contact WHERE AccountId = :acc.Id]) {
con.AccountId = acc.Id;
contactsToUpdate.add(con);
}
}
if (!contactsToUpdate.isEmpty()) {
update contactsToUpdate;
}
}

Integrating with External Systems

Apex Triggers can facilitate integrations with external systems by making callouts. Although synchronous callouts are not allowed in triggers, you can use @future methods to perform asynchronous callouts, enabling seamless data exchange between Salesforce and external systems.

Example:

trigger AccountTrigger on Account (after insert) {
List<Id> accountIds = new List<Id>();
for (Account acc : Trigger.new) {
accountIds.add(acc.Id);
}
AccountTriggerHandler.sendAccountData(accountIds);
}

public class AccountTriggerHandler {
@future(callout=true)
public static void sendAccountData(List<Id> accountIds) {
// Callout logic here
}
}

Creating Custom Notifications

Apex Triggers can be used to create custom notifications based on specific events. For example, a trigger can send an email notification to a manager when a high-priority case is created, ensuring timely attention to critical issues.

Example:

trigger CaseNotification on Case (after insert) {
for (Case c : Trigger.new) {
if (c.Priority == ‘High’) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] {‘manager@example.com’});
email.setSubject(‘High Priority Case Created’);
email.setPlainTextBody(‘A new high-priority case has been created: ‘ + c.Subject);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
}

By leveraging these advanced use cases for Apex Triggers, you can implement robust automation solutions that enhance data management, ensure data integrity, and facilitate seamless integrations within your Salesforce environment. These capabilities help in optimizing business processes and improving overall efficiency.

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. 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.

6. 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.

7. 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.

8. 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

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Salesforce Announces Dreamforce 2025: Dates and Key Details

Discover the latest updates on Dreamforce 2025, including dates, location, and what to expect from Salesforce’s premier event. Read now!

Salesforce Named a Leader in 2024 for Multichannel Marketing Hubs

Salesforce recognized as a Leader in 2024 Gartner Magic Quadrant for Multichannel Marketing Hubs, driving personalized, cross-channel engagement.

Salesforce October 2024 Updates by saasguru

Salesforce’s October 2024 updates bring AI innovations, partnerships, and recognitions, driving cloud solutions across industries. Read now!