Salesforce Apex Trigger Example: A Step-by-Step Guide

Apex triggers in Salesforce are powerful tools that enable developers to automate custom workflows and interactions when database events occur. Triggers execute logic before or after records are created, updated, deleted, or restored, making them essential for complex business processes.

This article provides a practical example of creating a Salesforce Apex Trigger to automate a business process.


What Is an Apex Trigger?

An Apex Trigger is a piece of code that automatically executes logic when specific events occur on Salesforce objects, such as:

  • Before Triggers: Execute logic before a record is saved to the database.
  • After Triggers: Execute logic after a record is saved.

Use Cases for Apex Triggers

  • Automating data updates.
  • Sending notifications or creating related records.
  • Enforcing complex validation rules.

Salesforce Apex Trigger Example

Objective

We’ll create a trigger that:

  1. Automatically updates the Account field on a Contact record when the contact’s email domain matches the account’s website domain.

Step 1: Prepare the Environment

  1. Log in to Salesforce:
    • Navigate to your Salesforce Developer Org.
  2. Enable Developer Console:
    • Open the Developer Console from the user dropdown menu.
  3. Prepare Sample Data:
    • Ensure you have Account and Contact records for testing.

Step 2: Create the Apex Trigger

  1. Navigate to Object Manager:
    • Go to SetupObject ManagerContactTriggers.
  2. Create a New Trigger:
    • Name the trigger UpdateContactAccount.

Add the Trigger Code:

trigger UpdateContactAccount on Contact (before insert, before update) {
    // Get all website domains of associated accounts
    Map<String, Id> domainToAccountId = new Map<String, Id>();
    for (Account acc : [SELECT Id, Website FROM Account WHERE Website != NULL]) {
        String domain = acc.Website.replace('http://', '').replace('https://', '').split('/')[0];
        domainToAccountId.put(domain, acc.Id);
    }

    // Iterate through contacts and update AccountId if email matches account domain
    for (Contact con : Trigger.new) {
        if (con.Email != null) {
            String emailDomain = con.Email.split('@')[1];
            if (domainToAccountId.containsKey(emailDomain)) {
                con.AccountId = domainToAccountId.get(emailDomain);
            }
        }
    }
}

Step 3: Test the Apex Trigger

Create Test Data

  1. Create an Account with a website:
    • Website: example.com.
  2. Create a Contact with an email address:
    • Email: user@example.com.

Test the Trigger

  1. Insert or update the Contact.
  2. Verify that the Account field on the Contact is automatically updated.

Step 4: Write an Apex Test Class

Salesforce requires test coverage for Apex triggers before deployment to production.

  1. Create a Test Class:
    • In the Developer Console, create a new Apex class named UpdateContactAccountTest.
  2. Run the Test Class:
    • In the Developer Console, navigate to TestNew Run → Select UpdateContactAccountTest → Click Run.

Add the Test Code:

@isTest
public class UpdateContactAccountTest {
    @isTest
    static void testUpdateContactAccount() {
        // Create an account
        Account testAccount = new Account(Name = 'Test Account', Website = 'example.com');
        insert testAccount;

        // Create a contact with a matching email domain
        Contact testContact = new Contact(FirstName = 'Test', LastName = 'User', Email = 'user@example.com');
        insert testContact;

        // Verify that the AccountId was updated
        testContact = [SELECT AccountId FROM Contact WHERE Id = :testContact.Id];
        System.assertEquals(testAccount.Id, testContact.AccountId);
    }
}

Step 5: Deploy the Trigger

  1. Ensure the test class achieves at least 75% code coverage.
  2. Deploy the trigger and test class to production using Change Sets or Salesforce CLI.

Best Practices for Apex Triggers

  1. Avoid Hard-Coding Logic:
    • Use custom metadata or settings for configurable rules.
  2. Use Context Variables:
    • Leverage Trigger.new, Trigger.old, and other context variables to access record data.
  3. Prevent Recursive Calls:
    • Use a static variable to avoid infinite loops when triggers call themselves.
  4. Write Bulk-Safe Code:
    • Always design triggers to handle bulk updates efficiently.

Conclusion

Apex triggers are a cornerstone of Salesforce automation, enabling developers to implement complex business logic efficiently. This example demonstrated how to create an Apex trigger that updates a contact’s account based on their email domain. By following best practices, you can build scalable and maintainable triggers to meet your organization’s unique requirements.