Writing your first apex trigger
Triggers are written to respond to the database changes and execute a set of business rule when these changes occur. Before we write a trigger let's understand the trigger and trigger handler class.
Trigger
Trigger is a piece of code written to act on database changes on a particular object. You should write only one trigger as an entry point the database changes for an object. If you write multiple triggers, your business calculations may not work as expected because the order of execution of a trigger is not guranteed in salesforce.
Trigger handler
A trigger handler is an apex class where the main logic for a trigger is written. The trigger itself should not contain any business logic. You can have one or more trigger handlers for an object in salesforce.
Trigger should only capture database events and then pass control to the trigger handler class to handle the business logic.
Trigger
Trigger Handler 1
Trigger Handler 2
Following is an example of an account trigger that sets the account industry to 'Technology' if the industry is blank:
In the above example:
Trigger
- The file
AccountTrigger
is a trigger written on Account object, which will be invoked before a new record is inserted (Before Insert event) into the database. - The apex class
AccountTriggerHandler
is implementing the business logic for the AccountTrigger, which is called from the trigger. - The trigger context variables
Trigger.isInsert
,Trigger.isBefore
, is used to conditionally invoking thehandleBeforeInsert
method from apex trigger. This is to make sure that trigger handler runs only for the Before Insert event.
Trigger Handler
- The apex class
AccountTriggerHandler
is the trigger handler. - The
Trigger.new
method is used to get all the records in the trigger context in the trigger handler. - The
Trigger.new
returns a list of Sobjects, which is conveted to a list of account records using typcasting in apex. - The
for
loop for collection is used to iterate through all records and set theIndustry
to 'Technology' if it is blank.
Note
Always use a list to operate on the records that invoke the trigger, this is called bulkification. The trigger can be invoked from a single record or a list of records (up to 200). Bulkification helps to reduce system resource usage and avoid hitting governor limit exceptions.