How to Write a Basic Trigger in Salesforce
Triggers in Salesforce are pieces of Apex code that execute before or after specific database-related events, such as insert, update, delete, or undelete operations on records. Let's explore some scenarios and examples of basic triggers written in Salesforce:
Scenario 1: Before Insert Trigger
In this scenario, we'll create a trigger that executes before inserting a new Account record and sets a default value for the Account's Industry field. Let's see the code:
trigger SetDefaultIndustry on Account (before insert) {
for (Account acc : Trigger.new) {
acc.Industry = 'Technology';
}
}
To test the trigger, follow these steps:
- Create a new Account record in Salesforce.
- Set any desired values for other fields, such as Account Name, Industry, etc.
- Save the record.
The trigger will automatically execute before the Account record is inserted, and the Industry field will be set to 'Technology'.
Scenario 2: After Update Trigger
In this scenario, we'll create a trigger that executes after updating an Opportunity record and displays a debugging result. Here's the code:
trigger DebugOnOpportunityUpdate on Opportunity (after update) {
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName == 'Closed Won' && oldOpp.StageName != 'Closed Won') {
System.debug('Opportunity ID: ' + opp.Id + ' has changed to Closed Won stage.');
}
}
}
To test the trigger, follow these steps:
- Update an existing Opportunity record in Salesforce.
- Change the Stage field to 'Closed Won'.
- Save the record.
After the update, check the Debug Logs in Salesforce to see the debugging result generated by the trigger.
Debugging Result:
Opportunity ID: [Opportunity ID] has changed to Closed Won stage.
0 Comments