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:
- Automatically updates the
Account
field on aContact
record when the contact’s email domain matches the account’s website domain.
Step 1: Prepare the Environment
- Log in to Salesforce:
- Navigate to your Salesforce Developer Org.
- Enable Developer Console:
- Open the Developer Console from the user dropdown menu.
- Prepare Sample Data:
- Ensure you have
Account
andContact
records for testing.
- Ensure you have
Step 2: Create the Apex Trigger
- Navigate to Object Manager:
- Go to Setup → Object Manager → Contact → Triggers.
- Create a New Trigger:
- Name the trigger
UpdateContactAccount
.
- Name the trigger
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
- Create an
Account
with a website:- Website:
example.com
.
- Website:
- Create a
Contact
with an email address:- Email:
user@example.com
.
- Email:
Test the Trigger
- Insert or update the
Contact
. - Verify that the
Account
field on theContact
is automatically updated.
Step 4: Write an Apex Test Class
Salesforce requires test coverage for Apex triggers before deployment to production.
- Create a Test Class:
- In the Developer Console, create a new Apex class named
UpdateContactAccountTest
.
- In the Developer Console, create a new Apex class named
- Run the Test Class:
- In the Developer Console, navigate to Test → New Run → Select
UpdateContactAccountTest
→ Click Run.
- In the Developer Console, navigate to Test → New Run → Select
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
- Ensure the test class achieves at least 75% code coverage.
- Deploy the trigger and test class to production using Change Sets or Salesforce CLI.
Best Practices for Apex Triggers
- Avoid Hard-Coding Logic:
- Use custom metadata or settings for configurable rules.
- Use Context Variables:
- Leverage
Trigger.new
,Trigger.old
, and other context variables to access record data.
- Leverage
- Prevent Recursive Calls:
- Use a static variable to avoid infinite loops when triggers call themselves.
- 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.