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

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.

Loading...

In the above example:

LeadTrigger

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

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

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

Loading...