In Salesforce, a trigger is a piece of Apex code that executes before or after specific data manipulation events occur, such as inserting, updating, deleting, or undeleting records. Triggers enable you to perform custom actions or validations when these events take place on Salesforce records.
Refer to the below links for more details -
Get Started with Apex Triggers
Apex Triggers
Define Apex Triggers
Here are some key points about triggers in Salesforce:
Execution Context: Triggers execute in response to specific database events and run in the Salesforce environment.
Supported Events: Triggers can be defined to execute before or after specific events, including insert, update, delete, undelete, and upsert.
Object-Specific: Triggers are associated with specific Salesforce objects, such as Accounts, Contacts, Opportunities, etc. Each trigger operates on records of its associated object type.
Apex Language: Triggers are written in Apex, Salesforce's proprietary programming language, which is similar to Java and C#. Apex provides a wide range of functionalities for handling data manipulation and business logic.
Custom Business Logic: Triggers allow developers to implement custom business logic that is not achievable through declarative tools like Workflow Rules or Process Builder. This includes complex validation rules, updating related records, sending notifications, etc.
Bulk Operations: Triggers are designed to handle bulk operations efficiently. Salesforce processes multiple records in a single transaction, and triggers are expected to handle these bulk operations without hitting governor limits.
Governor Limits: Salesforce imposes governor limits on the resources consumed by Apex code, including triggers, to ensure the stability and performance of the platform. Developers must write triggers with these limits in mind.
Context Variables: Triggers have access to context variables that provide information about the records being processed, the type of operation being performed, and other contextual details.
Overall, triggers are powerful tools in Salesforce for implementing custom business logic and automating processes based on data manipulation events within the Salesforce platform. However, they require careful design and testing to ensure they operate efficiently and within the platform's limits.
List of all context variables available for triggers
Here are a few examples of triggers in Salesforce:
Validation Trigger
trigger OpportunityValidationTrigger on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
if (opp.Amount > 1000000) {
opp.addError('Opportunity amount cannot exceed $1,000,000.');
}
}
}
Trigger to Update Related Records
trigger AccountAddressUpdateTrigger on Account (after update) {
List<Contact> contactsToUpdate = new List<Contact>();
for (Account acc : Trigger.new) {
if (acc.BillingStreet != Trigger.oldMap.get(acc.Id).BillingStreet ||
acc.BillingCity != Trigger.oldMap.get(acc.Id).BillingCity ||
acc.BillingState != Trigger.oldMap.get(acc.Id).BillingState ||
acc.BillingPostalCode != Trigger.oldMap.get(acc.Id).BillingPostalCode ||
acc.BillingCountry != Trigger.oldMap.get(acc.Id).BillingCountry) {
for (Contact con : [SELECT Id FROM Contact WHERE AccountId = :acc.Id]) {
con.MailingStreet = acc.BillingStreet;
con.MailingCity = acc.BillingCity;
con.MailingState = acc.BillingState;
con.MailingPostalCode = acc.BillingPostalCode;
con.MailingCountry = acc.BillingCountry;
contactsToUpdate.add(con);
}
}
}
update contactsToUpdate;
}
The trigger for Custom Notifications
trigger CaseNotificationTrigger on Case (after insert) {
List<Notification__c> notifications = new List<Notification__c>();
for (Case cas : Trigger.new) {
if (cas.Priority == 'High') {
Notification__c notification = new Notification__c();
notification.Subject__c = 'New High-Priority Case Created';
notification.Message__c = 'A new high-priority Case with subject "' + cas.Subject + '" has been created.';
notifications.add(notification);
}
}
insert notifications;
}
Salesforce Apex Trigger Best Practises
Bulkification: Write triggers to handle bulk data operations efficiently. Avoid using SOQL queries or DML statements inside loops, as this can lead to hitting governor limits. Instead, bulkify your code to process records in batches.
Use Trigger Context Variables: Utilize trigger context variables (Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap, Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete) to access the records and their attributes being processed by the trigger. This helps you write logic based on the context of the trigger execution.
Selective Queries: Only query the fields that you need. Minimize the number of SOQL queries inside triggers and use selective queries to retrieve only the necessary data.
Error Handling: Implement proper error handling to provide meaningful error messages and handle exceptions gracefully. Use addError() method to add custom error messages to records and rollback transactions when necessary.
Avoid Recursive Triggers: Prevent recursive trigger execution by using static variables or flags to track trigger recursion. Recursive triggers can lead to infinite loops and governor limit exceptions.
Separation of Concerns: Keep your trigger logic focused on a single concern. If your trigger becomes too complex, consider moving some of the logic to helper classes, utility methods, or trigger frameworks to maintain readability and manageability.
Use Annotations for Bulk Operations: Use annotations such as @future, @future(callout=true), and @Queueable for asynchronous processing or callouts to avoid long-running transactions and governor limit issues.
Unit Testing: Write comprehensive unit tests to ensure that your trigger logic works as expected under different scenarios and with different data volumes. Aim for high code coverage to catch any potential issues early.
Governor Limits Awareness: Be aware of Salesforce governor limits and design your triggers to stay within these limits. Monitor and optimize your code regularly to prevent hitting limits in production environments.
Documentation and Comments: Document your trigger logic clearly with comments to make it easier for other developers to understand and maintain the code in the future.
Here are some of the governor limits that are particularly relevant to Apex triggers
Total Number of DML Statements: Salesforce limits the total number of records that can be processed using DML (Data Manipulation Language) statements, such as insert, update, delete, or undelete, in a single transaction. This limit is currently set to 150 DML statements per transaction.
Total Number of SOQL Queries: Salesforce limits the total number of SOQL (Salesforce Object Query Language) queries that can be issued in a single transaction. This limit is currently set to 100 SOQL queries per transaction.
Total Number of Rows Retrived by SOQL Queries: There's also a limit on the total number of rows that can be retrieved by SOQL queries in a single transaction. This limit is currently set to 50,000 rows.
Total Heap Size: The total amount of memory allocated to Apex code, including triggers, is limited by the total heap size. This limit is currently set to 6 MB for synchronous transactions and 12 MB for asynchronous transactions.
Maximum CPU Time: Salesforce limits the maximum CPU time that can be consumed by Apex code in a single transaction. This limit is currently set to 10,000 milliseconds (10 seconds) for synchronous transactions and 60,000 milliseconds (60 seconds) for asynchronous transactions.
Maximum Number of Trigger Invocations: Salesforce limits the maximum number of times a trigger can be invoked per transaction. This limit is currently set to 200 for synchronous transactions and 50 for asynchronous transactions.
Maximum Depth of Trigger Recursion: Salesforce limits the maximum depth of trigger recursion, which prevents infinite loops caused by recursive triggers. This limit is currently set to 16.
Limits on Future Methods and Queueable Jobs: Asynchronous Apex methods, such as @future methods and Queueable Apex jobs, have their own set of limits, including limits on the number of future methods and queueable job invocations per transaction.
It's essential to be aware of these governor limits when designing and implementing triggers in Salesforce. Violating these limits can result in runtime exceptions and cause your transactions to fail. Therefore, it's crucial to design your triggers with these limits in mind and perform thorough testing to ensure that your code operates efficiently and stays within the governor's limits.
Comments
Post a Comment