0% found this document useful (0 votes)
52 views12 pages

Apex Trigger Concepts and Best Practices

Apex Triggers in Salesforce enable custom actions before or after record events like insertions, updates, and deletions. They are defined using specific syntax and context variables to manage record changes, and best practices include bulk processing and avoiding SOQL/DML in loops. Developers must also be aware of governor limits and ensure thorough testing for deployment readiness.

Uploaded by

sonawaneamol2021
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views12 pages

Apex Trigger Concepts and Best Practices

Apex Triggers in Salesforce enable custom actions before or after record events like insertions, updates, and deletions. They are defined using specific syntax and context variables to manage record changes, and best practices include bulk processing and avoiding SOQL/DML in loops. Developers must also be aware of governor limits and ensure thorough testing for deployment readiness.

Uploaded by

sonawaneamol2021
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Apex Trigger: Concepts and Notes

Apex Trigger is a special type of code that allows you to perform custom
actions before or after events on a record in Salesforce, such as insertions,
updates, deletions, or merges. Triggers are written in Apex, a programming
language developed by Salesforce.

Key Concepts of Apex Triggers

1. Trigger Events: Triggers can execute at specific points in the lifecycle of


a record. There are two categories of trigger events:
o Before Triggers: Used to update or validate record values before
they are saved to the database.
o After Triggers: Used to perform operations (like sending emails or
making changes to related records) after the record has been saved.
2. Trigger Syntax:

trigger TriggerName on ObjectName (trigger_events) {


// Trigger logic here
}

o TriggerName: The name of your trigger.


o ObjectName: The Salesforce object the trigger is applied to (e.g.,
Account, Contact).
o trigger_events: The specific events (e.g., before insert, after
update) when the trigger should fire.

Example:

trigger AccountTrigger on Account (before insert, after update) {


// Logic goes here
}

3. Context Variables: Salesforce provides special variables to help you


manage records within a trigger. Some important ones are:
o [Link]: Contains new versions of the records being inserted
or updated.
o [Link]: Contains old versions of the records (useful in
update/delete triggers).
o [Link]: Returns true if the trigger was fired due to an
insert operation.
o [Link]: Returns true if the trigger was fired due to an
update.
o [Link]: Returns true if the trigger was fired due to a
delete operation.
4. Trigger Execution Flow:
o When a trigger fires, the following steps typically happen in this
order:
1. Before Triggers: Validation, data changes, etc.
2. System Validations: Standard Salesforce validation rules.
3. After Triggers: Complex logic or actions that rely on
records being committed to the database.
4. Workflow Rules: Automation rules that might trigger
further updates or actions.
5. Commit: Data is saved to the database.
6. Post-commit logic: Sending emails, creating tasks, etc.
5. Types of Triggers:
o Before Insert
o After Insert
o Before Update
o After Update
o Before Delete
o After Delete
o After Undelete
6. Trigger Best Practices:
o Bulkify Code: Always write triggers to handle multiple records at
once (bulk processing). Use loops and collections (e.g., List, Set)
rather than operating on a single record at a time.
o Avoid SOQL/DML in Loops: Do not place SOQL queries or
DML operations inside loops, as it can lead to governor limit
issues.
o Use Helper Classes: Move complex logic to a separate class for
easier maintenance and readability.
o Test Coverage: Ensure at least 75% of your trigger is covered by
test classes for deployment.

Example: Simple before insert Trigger

Let’s say you want to set a default value for a custom field on Account before
the record is inserted:
This trigger runs before any new Account record is inserted and ensures that if
the Industry field is left blank, it defaults to "Technology."

Example: after insert Trigger for Updating a Related Object

If you need to update related Contacts after inserting an Account, you could
write a trigger like this:

Governor Limits to Keep in Mind

Salesforce enforces certain limits (known as governor limits) to ensure


efficient use of resources. When writing triggers, you need to be mindful of
these:

 Maximum SOQL Queries per transaction: 100.


 Maximum DML statements per transaction: 150.
 Maximum CPU time per transaction: 10,000 ms.
Testing Triggers

Every trigger should have an accompanying test class to validate that it behaves
as expected. Example:

Summary

 Apex Triggers allow for customized business logic tied to record events
(like insert/update/delete).
 Before triggers allow for data manipulation before saving to the
database, while after triggers operate once the data is saved.
 Always write triggers with bulk operations in mind, avoid SOQL in
loops, and leverage helper classes.

Test your trigger logic with unit tests to ensure code coverage and
correctness.

Apex Triggers: Full Notes on All Key Concepts

Apex Triggers allow Salesforce developers to define custom behavior for


different events, such as when records are inserted, updated, or deleted. Triggers
are a powerful way to automate tasks and enforce business rules at the database
level. Below are the full notes covering all the essential concepts around Apex
Triggers.

1. What is an Apex Trigger?


An Apex Trigger is a piece of code that is executed before or after a specific
event occurs to a record in Salesforce. Triggers allow you to perform operations
like updating related records, enforcing custom validation rules, and automating
tasks.

2. Trigger Events

Triggers can respond to the following events on Salesforce records:

 Before Insert: Fired before a record is inserted into the database.


Typically used to validate or modify record values before they are saved.
 After Insert: Fired after a record has been inserted into the database.
Used for actions like updating related records or sending emails.
 Before Update: Fired before a record is updated. Used to modify or
validate the record before committing changes to the database.
 After Update: Fired after a record is updated in the database. Used to
interact with related records or perform complex business logic.
 Before Delete: Fired before a record is deleted from the database. Used
to check dependencies or restrict deletion.
 After Delete: Fired after a record is deleted from the database. Often
used for clean-up operations.
 After Undelete: Fired after a record is restored from the Recycle Bin.
Typically used to reinstate relationships or data that might have been
affected by deletion.

3. Trigger Syntax

Triggers follow a specific syntax in Salesforce. Here’s a basic structure:

apex

trigger TriggerName on ObjectName (trigger_events) {


// Logic goes here
}

 TriggerName: Name of the trigger.


 ObjectName: The object on which the trigger acts (e.g., Account,
Contact).
 trigger_events: The events that will fire the trigger (e.g., before insert,
after update).
Example:

apex
trigger AccountTrigger on Account (before insert, after update) {
// Trigger logic
}

4. Trigger Context Variables

Salesforce provides several context variables that can be used within triggers
to manage and manipulate records. These variables help identify what type of
event triggered the code and allow access to the records involved.

Common Context Variables:

 [Link]: Returns a list of new records that are being inserted or


updated (for insert and update events).
 [Link]: Returns a list of old records that are being updated or
deleted (for update and delete events).
 [Link]: Returns true if the trigger was fired by an insert event.
 [Link]: Returns true if the trigger was fired by an update
event.
 [Link]: Returns true if the trigger was fired by a delete event.
 [Link]: Returns true if the trigger was fired before a record
was saved.
 [Link]: Returns true if the trigger was fired after a record was
saved.
 [Link]: A map of IDs to the new records (used for update and
insert events).
 [Link]: A map of IDs to the old records (used for update and
delete events).
Example:

5. Trigger Execution Order

Salesforce processes multiple triggers and actions in a specific sequence to


ensure data consistency. The typical execution order is:

1. Before Triggers: Validate or update values before the record is


committed.
2. System Validations: Standard Salesforce validations (e.g., required
fields, field formats) are performed.
3. After Triggers: Perform actions based on the saved data (updating
related objects, sending emails, etc.).
4. Workflow Rules: Automation rules such as Workflow and Process
Builder may modify the data further.
5. Commit: The data is finally committed to the database.
6. Post-commit Logic: Actions that depend on the committed data, such as
email notifications or outbound messages, are executed.

6. Trigger Best Practices

To ensure that your triggers are efficient, maintainable, and scalable, follow
these best practices:

6.1. Bulkify Your Code

Triggers should always handle multiple records (bulk operations). Salesforce


triggers can process up to 200 records at a time. Your code should avoid
operating on a single record and instead use loops and collections.
Example:

6.2. Avoid SOQL Queries/DML Statements in Loops

Executing SOQL queries or DML operations inside loops can quickly exceed
Salesforce’s governor limits, leading to runtime errors. Always move queries
and DML operations outside of loops.

Bad Example (SOQL in a loop):

apex

for(Account acc : [Link]) {


List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId =
:[Link]];
}

Better Example:

apex

List<Id> accountIds = new List<Id>();


for(Account acc : [Link]) {
[Link]([Link]);
}
List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId IN
:accountIds];
6.3. Use Helper Classes

Move complex logic from the trigger to a separate helper class. This approach
improves code maintainability and reusability.

Example:

6.4. One Trigger per Object

Maintain only one trigger per object to avoid conflicts and to ensure a clear
execution order. Use helper methods to manage complex logic.

6.5. Write Test Classes

Every trigger should be accompanied by a test class to ensure that the trigger
behaves as expected and meets the required test coverage (at least 75% for
deployment).

7. Governor Limits

Salesforce imposes governor limits to ensure that no single process consumes


too many resources. When writing triggers, you must be mindful of these limits.

Common Limits to be aware of:


 SOQL Queries: Maximum of 100 queries per transaction.
 DML Statements: Maximum of 150 DML operations per transaction.
 CPU Time: Maximum of 10,000 milliseconds for each transaction.
 Heap Size: Maximum heap size of 6 MB (12 MB for asynchronous).

8. Trigger Example: Bulk Insert Handling

Here’s an example trigger that sets the Industry field to "Technology" if it’s null
and updates related Contacts after an Account is inserted:

9. Testing Triggers

Testing is essential to ensure that your trigger logic works correctly. You need
to write test classes with assertions to confirm expected behavior. Here’s an
example of a test class for the AccountTrigger:
10. Trigger vs Process Builder vs Flow

 Triggers: Allow for more complex, low-level control but require Apex
coding.
 Process Builder/Flow: Provide declarative automation tools for simpler
logic and actions but have some limitations in terms of complexity.

Conclusion

Apex Triggers are essential for automating business logic in Salesforce. By


understanding trigger events, context variables, best practices (like
bulkification), and governor limits, developers can write efficient and
maintainable code that handles Salesforce records in bulk and interacts with
related objects. Always ensure to test your triggers thoroughly with unit tests to
maintain high-quality code and compliance with Salesforce deployment
requirements.
🎁 Want 20+ Interview Scenarios + Solutions + Code?

🔗 500+ Dev & Admin Q&A (Infosys, EY, Dell…)


👉 [Link]

🔗 100 Apex Trigger Questions Pack


👉 [Link]

🔗 LWC Interview Q&A + My Answers


👉 [Link]

🔗 Salesforce Interview Master Pack


👉 [Link]

🔗 34-Day Battle Plan


👉 [Link]

You might also like