What are Apex Triggers ?
Apex triggers are a powerful tool in the Salesforce platform that allow developers to automate actions in response to specific events, such as the creation or update of a record.
Triggers are written in Apex, Salesforce's proprietary programming language, and can be used to perform a wide range of tasks, such as updating related records, sending notifications, and enforcing data validation rules.
To create a trigger, a developer must first define the trigger's event (e.g., "before insert"), the object it applies to (e.g., "Account"), and the Apex code to be executed when the trigger fires.
When an event that matches the trigger's criteria occurs, the Apex code is executed. This code can access the record that caused the trigger to fire and perform any necessary actions.
One important aspect of Apex triggers is governor limits, which are resources that Salesforce makes available to Apex code. These limits include the number of database operations, the number of script statements, and the amount of memory used.
How to create a new Apex trigger ?
To create a new Apex trigger in Salesforce, you can follow these steps:
- Go to Setup in the top right corner of your Salesforce account and click on "Apex Triggers" under the "Develop" menu.
- Click on the "New" button to create a new trigger.
- In the "Apex Trigger" page, you need to specify the following information:
- The name of the trigger
- The object that the trigger applies to
- The event that triggers the execution of the trigger (e.g., "before insert", "after update")
- The Apex code to be executed when the trigger fires
- Once you have entered all the required information, click on the "Save" button to create the trigger.
- You can then test your trigger by performing the actions that are specified in the trigger's event. For example, if your trigger is set to fire "before insert" on the "Contact" object, you can test it by creating a new contact record.
- After you've tested and confirmed that the trigger is working as expected, you can deploy it to a production environment.
Example Of An Apex Trigger ?
Below I am giving example of an Apex trigger that updates the "LastModifiedBy" field on the "Contact" object every time a contact record is updated:
trigger UpdateLastModifiedBy on Contact (before update) { // Get the current user's ID Id userId = UserInfo.getUserId(); // Loop through the list of updated contacts for (Contact c : Trigger.new) { // Update the LastModifiedBy field with the current user's ID c.LastModifiedBy = userId; } }
In this example, the trigger is defined to fire "before update" on the "Contact" object. The code uses the "Trigger.new" variable, which contains a list of the records that are being updated, to loop through each contact and update the "LastModifiedBy" field with the ID of the current user.
Another example I would like to give is, if we have a requirement that, whenever an account is created, a case record should also be created.
trigger CreateCase on Account (after insert) { // Create a list to store the new cases List<Case> newCases = new List<Case>(); // Loop through the list of newly created accounts for (Account a : Trigger.new) { // Create a new case related to the account Case c = new Case(); c.AccountId = a.Id; c.Subject = 'Case related to account ' + a.Name; c.Description = 'This is a case automatically created when the account was created.'; c.Status = 'New'; // Add the case to the list newCases.add(c); } // Insert the new cases insert newCases; }
In this example, the trigger is defined to fire "after insert" on the "Account" object. The code uses the "Trigger.new" variable, which contains a list of the records that are being inserted, to loop through each account and create a new case record related to the account. The case record is then added to a list, and then all the case records are inserted at once using the insert statement.
What are the Governor Limits of Apex triggers ?
- In one transaction, you can use a maximum of 100 SOQL queries.
- In one transaction, you can use a maximum of 20 SOSL queries.
- In one transaction, you can use a maximum of 150 DML statements.
- In one transaction, you can fetch a maximum of 50k records in SOQL.
- In one transaction, you can fetch a maximum of 2k records in SOSL.
What are Limitations of Apex Triggers ?
- Concurrent Apex requests: Apex triggers can't be run concurrently, so it's possible that a second request may be blocked by the first request that is still running.
- Apex triggers don't support rollback operations, which means that if a trigger fails, any changes made by the trigger cannot be undone.
- Triggers can't be called or invoked directly: Triggers are automatically invoked by Salesforce based on the DML operations that are performed. They can't be invoked directly by Apex code or by a user.
How to write a test class for Apex Trigger ?
To test an Apex trigger test class, you can use the @isTest
annotation and the Test.startTest()
and Test.stopTest()
methods to create test methods that simulate the conditions under which the trigger will fire. Here is an example of a test class for an Apex trigger:
This is a test class for same example I have given for Updating last modified by when contact is updated.
@isTest private class UpdateLastModifiedByTest { @isTest static void testUpdateLastModifiedBy() { // Create a test user User testUser = new User(Username='testuser@example.com', Email='testuser@example.com', LastName='Test', Alias='testuser', TimeZoneSidKey='America/Los_Angeles', LocaleSidKey='en_US', EmailEncodingKey='UTF-8', ProfileId='00e28000001YfYQ'); insert testUser; // Create a test contact Contact testContact = new Contact(LastName='Test'); insert testContact; // Switch to the test user System.runAs(testUser) { // Update the test contact testContact.FirstName = 'John'; update testContact; } // Verify that the LastModifiedBy field was updated Contact updatedContact = [SELECT LastModifiedBy FROM Contact WHERE Id = :testContact.Id]; System.assertEquals(testUser.Id, updatedContact.LastModifiedBy); } }
Conclusion
Overall, Apex triggers are a powerful tool for automating actions in Salesforce, but they must be used responsibly to ensure that they do not negatively impact performance. With the right design, triggers can help streamline business processes and make the Salesforce platform even more powerful.
Sahil is a highly skilled and dedicated Salesforce Certified Platform Developer with a passion for creating efficient and innovative solutions within the Salesforce ecosystem. With an insatiable curiosity and a relentless drive for excellence, he has become a go-to expert in developing custom applications and functionalities on the Salesforce platform.
Comments are closed.