Table of Contents
What is an Apex Trigger
A Trigger is an Apex Script that immediately executes before and after a DML operation occurs. Then it performs some custom actions like insertions, deletion, and updating the records. Generally, in Database systems, we use triggers for some actions and in the same way in salesforce, triggers are used to perform actions in the salesforce database.
Operations in Apex Trigger
There are two operations in triggers they are:
- Before triggers: Before triggers are used when you need to perform any specific actions before the DML operation occurs like updating the field.
- After triggers: After triggers are used when you need to perform any specific actions After the DML operation occurs, mostly we use After triggers when we need to use any System generated values.
Events in Apex Trigger
There are 7 different events in triggers, they are:
Before events: They are used when you need to perform any specific action before insertion or deletion or updating the records.
- Before insert
- Before update
- Before delete
After events: They are used when you want to perform any specific action after insertion or deletion or updating the records or undeleting.
- After insert
- After update
- After delete
- After undelete
Syntax to create sample trigger
Syntax:
trigger TriggerName on ObjectName (trigger_events) { code_block }
This is the simple syntax to write a trigger. Writing trigger keyword, then trigger name and then object name you want to perform on and then trigger events in the brackets. Finally, code to be executed after the event in the curly braces.
Example
This is an example of after trigger, what it does is to create an Account record whenever a Contact record is created without an Account.
trigger ContactCustomTriggerExample on Contact (after insert) { List<Account> accListToInsert = new List<Account>(); for(Contact con : Trigger.New) { if(con.AccountId == null ) { Account acc = new Account(); acc.Name = con.LastName; acc.Phone = con.Phone; accListToInsert.add(acc); } } if(!accListToInsert.isEmpty()){ insert accListToInsert; } }
Output
The output of the code will be creation of an Account object automatically whenever a Contact record is created without the Account.
Code Explanation
Here, we have created a list object accLidtToInsert in line 2, then using a for loop which for every contact checks whether its accountId field is null or not, using an if condition. And if true, new Account with the same name and phone are created and added to the created list. Then via an if condition, if the list is not empty then it is inserted into the database using the insert command.
0 Comments