Getting Started with Apex Triggers in Salesforce
Apex triggers are one of the most powerful tools in a Salesforce developer’s toolkit. They allow you to execute custom code before or after DML operations on Salesforce records.
What is an Apex Trigger?
An Apex trigger is a piece of code that executes before or after specific data manipulation language (DML) events occur, such as before records are inserted into the database or after records are deleted.
Trigger Syntax
trigger TriggerName on ObjectName (trigger_events) {
// code_block
}
Trigger Context Variables
Salesforce provides several context variables that give you access to the records being processed:
- Trigger.new - Returns a list of the new versions of the sObject records
- Trigger.old - Returns a list of the old versions of the sObject records
- Trigger.isInsert - Returns true if the trigger was fired due to an insert operation
- Trigger.isUpdate - Returns true if the trigger was fired due to an update operation
- Trigger.isDelete - Returns true if the trigger was fired due to a delete operation
Best Practices
- One trigger per object - Consolidate all logic into a single trigger per object
- Use trigger handlers - Move logic out of the trigger into a handler class
- Bulkify your code - Always handle collections, not single records
- Avoid SOQL in loops - Query outside of loops to stay within governor limits
Example: Account Trigger
trigger AccountTrigger on Account (before insert, before update) {
AccountTriggerHandler handler = new AccountTriggerHandler();
if (Trigger.isInsert) {
handler.onBeforeInsert(Trigger.new);
} else if (Trigger.isUpdate) {
handler.onBeforeUpdate(Trigger.new, Trigger.oldMap);
}
}
Conclusion
Apex triggers are essential for any Salesforce developer. By following best practices and understanding the trigger context, you can build robust and efficient automation for your Salesforce org.
Leave a Comment