Setting default values
Before triggers can be used to set default values on the record before records are saved into the database. This automation helps users not requiring all fields to fill in from the UI when creating records thus saving more time.
A real-world example would be automatically setting up your billing country when you're purchasing something from an e-commerce website.
Following is an example of a before trigger which sets the lead source as 'Web' when a new record is inserted.
In the above example:
LeadTrigger
The
trigger
is defined on thelead
object and will be invoked for theBefore Insert
event.The
Trigger.isBefore
andTrigger.isInsert
are used to conditionally check the trigger context before invoking the trigger handler.The trigger handler
LeadTriggerHandler
is used to handle the trigger logic.
LeadTriggerHandler
The class
LeadTriggerHandler
implements the business logic for theLeadTrigger
To access the new version of records in the trigger handler, the
Trigger.new
context variables is used, which will return a list of sObjects in the context.The list of Sobjects from
Trigger.new
is type-cast to Lead records using(List<Lead>) Trigger.new;
The lead collection is iterated using for loop collection and set the source as 'Web'