Table of Contents
Introduction
Triggers are the complex structures used in salesforce when things are not getting done using Workflow, Process builders or Flows. Well, they are complex to write and effective in execution.
What is Trigger in Salesforce
A trigger is an Apex Script which is automatically triggered after or before the DML operation. It enables you to perform actions like insertions, updates or deletions on a record. Using Triggers we can do a lot of things like executing DML, SOQL and even calling apex methods.
When to use Salesforce triggers
As said earlier, Salesforce triggers can be used when things are not happening in declarative approaches like using workflows, Process builders or Flows. As in triggers, we can write code, we can perform any activity with our coding knowledge.
Trigger Syntax
Trigger syntax is simple,
trigger TriggerName on ObjectName (trigger_events) code_block }
This is as simple as Writing a keyword “trigger” and then trigger name followed by the object name we are going to perform on and specifying the trigger events.
Now let’s dive into the various trigger events.
Trigger events in Salesforce
Here, we have a list of trigger events that can be used in writing triggers, these can be written in a comma-separated form in the trigger syntax.
- before insert
- before update
- before delete
- after insert
- after update
- after delete
- after undelete
Different type of Triggers
There are two types of triggers,
- Before trigger:
Before trigger is used to perform a task before the event, like before insertion, updating or deletion of the records. Mostly “before triggers” are used to update the record values before they are saved.
- After trigger:
After trigger is used to perform a task after the event, like after insertion, updating or deletion of the records. Mostly “after triggers” are used to set the system values to the records like Id or LastModifiedDate.
Salesforce Trigger Example
Example trigger on Account
trigger AddT0Account on Account (before insert, before update) { for(Account acc1 : Trigger.New) { if(acc1.Industry != null && (acc1.Industry == 'Banking' || acc1.Industry == 'Healthcare')){ acc1.Rating = 'Hot Industry'; } } }
Here, in this trigger whenever an Account record is created or updated, immediately the trigger will execute whether the Industry field is “Banking” or “Healthcare”, if so it will automatically update the Rating field to “Hot Industry”.
0 Comments