This course is currently a work in progress. Please join the waitlist to receive regular updates.

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'.

Loading...

OpportunityTrigger

  • The trigger is defined on the Opportunity object and will be invoked for the Before Insert event.

  • The Trigger.isBefore and Trigger.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 the OpportunityTrigger

  • 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'

Loading...
Loading...