Field updates in apex triggers
Before apex triggers can be used to update the field values on the record before it is saved. This is another automation that helps reduce manual effort and minimize data errors in the database.
A real-world example would be automatically setting up your billing address based on the shipping address.
Following is an example of an apex trigger which updates the opportunity lead source as 'Web' if the opportunity type is 'New Customer'.
OpportunityTrigger
The
trigger
is defined on theOpportunity
object and will be invoked for theBefore Insert
event.The
Trigger.isBefore
andTrigger.isInsert
context variables are used to conditionally check the trigger context before invoking the trigger handler.The trigger handler
OpportunityTriggerHandler
is used to handle the trigger logic.
OpportunityTriggerHandler
The class
OpportunityTriggerHandler
implements the actual business rules for theOpportunityTrigger
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 Opportunity records using(List<Opportunity>) Trigger.new;
The for loop collection is used to iterate the records and sets the leadSource as
'Web'
if the opportunity type is'New Customer'