Triggers in Salesforce
A trigger in Salesforce is a piece of code that executes before or after a specific event occurs on a record in the Salesforce database. Triggers in Salesforce are used to automate business processes, enforce data validation rules, and perform custom actions on records in response to changes in the Salesforce environment.
When a record is created, updated, deleted, or undeleted in Salesforce, the trigger code associated with that event is executed. The trigger code can access and modify the data in the record, as well as other related records. Do you want to become a sought-after Salesforce professional in one of India’s thriving tech hubs? Look no further! Our Salesforce Course in Pune is your gateway to success in the world of cloud-based customer relationship management.
Triggers can be created using Apex Salesforce programming language. Apex code is executed on the Salesforce platform and can be written using a variety of tools, including the Salesforce Developer Console, Visual Studio Code, and other integrated development environments (IDEs).
For Free, Demo classes Call: 020-711-73102
Registration Link: Click Here!
Two Types of Triggers in Salesforce:
Before Triggers: These triggers are executed before the record is saved to the database. Before triggers can be used to modify the data in the record or perform additional data validation checks.
After Triggers: These triggers are executed after the record is saved to the database. After triggers can be used to perform additional actions on the record or related records.
Trigger Syntax
Triggers are written in Apex, Salesforce’s programming language. Here’s the basic syntax for a trigger:
Code
trigger TriggerName on ObjectName (trigger_events) {
// trigger logic
}
TriggerName is the name of the trigger.
ObjectName is the name of the object that the trigger is associated with.
trigger_events is a comma-separated list of events that the trigger should fire on, such as before insert, after update, etc.
The trigger logic goes inside the curly braces.
Here’s an example of a trigger that fires before an Account record is inserted:
Code:
trigger AccountTrigger on Account (before insert) {
// trigger logic
}
Use Cases for Triggers
Triggers can be used for a wide variety of purposes in Salesforce. Here are some common use cases for triggers:
Enforcing Business Rules: Triggers can be used to enforce business rules, such as validating data or setting default field values. For example, a trigger can be used to ensure that a new Opportunity is assigned to a specific sales rep based on the record’s industry.
For Free, Demo classes Call: 020-711-73102
Registration Link: Salesforce Training in Pune!
Automating Processes: Triggers can be used to automate processes, such as sending email notifications or updating related records. For example, a trigger can be used to send an email to the account owner when a new Opportunity is created.
Integrating with External Systems: Triggers can be used to integrate with external systems, such as updating a customer record in an external system when a related record is updated in Salesforce.
Customizing User Interfaces: Triggers can be used to customize user interfaces, such as hiding or displaying fields based on the value of other fields.
Best Practices for Triggers
When writing triggers in Salesforce, it’s important to follow best practices to ensure that your code is efficient, maintainable, and scalable. Here are some best practices for writing triggers:
Use Trigger Handlers: Instead of putting all of your trigger logic in a single trigger, use a trigger handler class to separate your logic into smaller, more manageable pieces. This makes your code more modular and easier to maintain.
Minimize SOQL Queries: SOQL queries are a common source of performance issues in triggers. To avoid performance problems, minimize the number of SOQL queries you use in your triggers.
Avoid Hard-Coded IDs: Avoid hard-coding IDs in your triggers, as this can make your code less flexible and harder to maintain. Instead, use dynamic SOQL queries to retrieve record IDs based on other criteria.
Test Your Triggers: Always test your triggers thoroughly to ensure that they work as expected. Use unit tests to verify that your triggers handle different scenarios and edge cases correctly.
Follow the Governor Limits: Salesforce imposes a number of governor limits on triggers, such as limits on the number of queries and the amount of data that can be processed. Be sure to follow these limits to ensure that your triggers run efficiently and don’t hit any performance limits.
For Free, Demo classes Call: 020-711-73102
Registration Link: Click Here!
Examples of Triggers in Salesforce:
1.trigger AccountTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.Name.contains(‘Test’)) {
acc.Description = ‘This is a test account.’;
}
}
}
In this trigger, we’re updating the description of any new or updated account records that have “Test” in their name. We’re using the before insert and before update events, which means that the trigger will fire before the records are saved to the database. We’re also using a for loop to iterate over the records in the trigger context (Trigger.new) and update their descriptions if the name contains “Test”. This is a simple example, but triggers can be much more complex and can perform a wide variety of actions based on the records being modified.
trigger AccountTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.Name.contains(‘Test’)) {
acc.Description = ‘This is a test account.’;
}
}
}
In this trigger, we’re updating the description of any new or updated account records that have “Test” in their name. We’re using the before insert and before update events, which means that the trigger will fire before the records are saved to the database. We’re also using a for loop to iterate over the records in the trigger context (Trigger.new) and update their descriptions if the name contains “Test”. This is a simple example, but triggers can be much more complex and can perform a wide variety of actions based on the records being modified.
- Automatically update a Contact’s mailing address when their associated Account’s billing address is updated. Here’s how you can write a trigger to accomplish this:
Note: SevenMentor’s Salesforce course in Pune covers everything from the fundamentals to advanced topics.
Code
trigger UpdateContactMailingAddress on Account (after update) {
// Get a list of all the Account records that were updated
List<Account> updatedAccounts = Trigger.new;
// Create a list of Contact records to update
List<Contact> contactsToUpdate = new List<Contact>();
// Loop through each updated Account record
for (Account acc : updatedAccounts) {
// Check if the BillingStreet, BillingCity, BillingState, or BillingPostalCode fields were changed
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) {
// Get a list of all the Contact records associated with this Account
List<Contact> contacts = [SELECT Id, MailingStreet, MailingCity, MailingState, MailingPostalCode FROM Contact WHERE AccountId = :acc.Id];
// Loop through each Contact record and update its mailing address
for (Contact con : contacts) {
con.MailingStreet = acc.BillingStreet;
con.MailingCity = acc.BillingCity;
con.MailingState = acc.BillingState;
con.MailingPostalCode = acc.BillingPostalCode;
contactsToUpdate.add(con);
}
}
}
// Update the Contact records
update contactsToUpdate;
}
Do Watch our video on: What is Salesforce?
In this trigger, we’re using the after-update event to trigger the code when an Account record is updated. We’re checking if the BillingStreet, BillingCity, BillingState, or BillingPostalCode fields were changed on the updated Account records. If they were, we’re querying for all the Contact records associated with that Account and updating their mailing address fields. Finally, we’re updating the Contact records with the new mailing address values.
Author:-
Komal Wavare
Call the Trainer and Book your free demo Class For Salesforce Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.