Apex Triggers in Salesforce
Apex triggers are used to achieve automation in Salesforce and used to perform different kind of operations and actions before or after events to records in Salesforce, such as insertions, deletions, or updates. Apex also provides support to trigger for managing records in Salesforce. Read more at Salesforce Course in Pune.
Trigger can be used to do anything you can do in Apex, including executing SOQL and DML or calling custom Apex methods.
Which actions or operation can’t be performed by using the point-and-click tools in the Salesforce user interface, we can achieve those using Apex Trigger. For example, if we are going to update a field value or validating a field on a record, we use validation rules and workflow rules instead.
We can write apex trigger for standard objects, custom objects, and some standard child objects.
Trigger syntax is different from a class definition’s syntax. Trigger definition syntax starts with the ‘trigger’ keyword. After ‘trigger’ keyword you have to write the trigger name and mention the event when you want to perform the actions.
A trigger has the following syntax:
trigger TriggerName on ObjectName (trigger_events)
Types of Triggers:
There are two types of triggers.
- Before triggers: It is used to update the records or validate the values of records before they’re saved to the database.
- After triggers: It is used to get or retrieve values of fields that are generated by the system (such as a record’s Id), and to affect changes in other records.
Trigger’s events are those which enforce the trigger to run as the changes in the records, like insert, delete, update, and undelete operations, specify multiple trigger events in a comma-separated list. The events you can specify are:
- before insert
- before update
- before delete
- after insert
- after update
- after delete
- after undelete
Here is an example of trigger executes or fires before you insert an account and writes a message to the debug log.
- In your Salesforce ORG, Open the Developer Console, click File | New | Apex Trigger.
- Enter the trigger name DemoTrigger, and then select Account for the sObject. Click Submit.
- Rewrite the code with the following code.
trigger DemoTrigger on Account (before insert)
- To save, press Ctrl+S.
- Create an Account record to test the trigger.
- Click on the Debug | Open Execute Anonymous Window.
- Inside the opened Anonymous window, add the following and then click Execute.
Account a = new Account(Name=’Test Trigger’);
- Open the debug log, search for the Hello World! Statement. In the log file we can also check that the trigger has been executed.
Trigger Context Variables:
In the trigger code, Context variable is used to access records that caused the trigger to fire. As Trigger.New is having all the records that were inserted using insert or update triggers. Trigger.Old context variable can be used to hold the old version of sObjects before they were updated in update triggers, or a list of sObjects, which is deleted in delete triggers.
The following table is a list of all context variables available for triggers.
|isExecuting||This context variable gives the value true if the running context for the Apex code is a trigger only, not a Visualforce page, a Web service, or an executeanonymous() API call.|
|isInsert||It will give the true value when trigger was executed because of an insert operation, from Apex or the API and the Salesforce user interface.|
|isUpdate||It will return true value if the trigger was executed due to an update operation, from Apex or the API and the Salesforce user interface.|
|isDelete||It will give the true value when the trigger was execute or fired because of a delete operation, from the Salesforce user interface, Apex, or the API.|
|isBefore||It will give the true value when the trigger was fired before any record was saved.|
|isAfter||The context variable returns true if the trigger was execute after all records were saved.|
|isUndelete||It is used to return true if this trigger was fired or executed after a record is recovered from the Recycle Bin.|
|new||The context variable is used to contain a list of the new versions of the sObject records. |
The records can only be modified or customized in before triggers. sObject’s list is present only in insert trigger, undelete trigger and update triggers.
|newMap||It is used to contain the map of IDs to the new versions of the sObject records. |
In before update, after insert, after update, and after undelete triggers, it’s available.
|old||The context variable basically returns or contains a list of the old versions of the sObject records. |
The list of sObjects is only present in delete and update triggers.
|oldMap||Maps return by oldMap context variable is only present in update and delete triggers and contain the map of IDs to the old versions of the sObject records.|
|operationType||This context variable basically returns an enum of type System.TriggerOperation corresponding to the current operation. |
System.TriggerOperation enum can have different type of values such as BEFORE_INSERT, AFTER_INSERT.
|size||This context variable is used to return the total number of records in a trigger invocation, both old and new.|
This example is a modified version of the DemoTrigger example trigger. This trigger will be execute for each account in a for loop and updates the Description field for each.
trigger DemoTrigger on Account (before insert)
for(Account a : Trigger.New)
a.Description = ‘New description’;
Apex Trigger Best Practices:
1) One Trigger per Object
Single Apex Trigger is all Salesforce Training in Pune need for one particular object. When multiple Triggers are written for a single object is written then you cannot control the order of execution if those Triggers can run in the same contexts
2) Logic-less Triggers
If you write methods in Triggers, those can’t be exposed for test purposes. You also will not be able to expose the logic to be re-used anywhere else in your org.
3) Context-Specific Handler Methods
In Trigger handlers we should create context specific handler methods.
4) Bulkify your Code
Writing bulkify code then it refers to the concept of making sure the code properly handles more than one record at a time.
5) Avoid DML statements and SOQL Queries inside FOR Loops
There are number of SOQL queries issued is 100 in an apex transaction before exceeding that governor limit. So if there are more than 100 Account records and we fire the trigger then the governor limit will exceed and throw a runtime exception
For more details, you can take reference from here: Salesforce Classes in Pune by Seven Mentor
Call the Trainer and Book your free demo Class for now!!!
© Copyright 2021| Sevenmentor Pvt Ltd.