Developer 1 - Trigger Basics

4 - Intro to Apex Triggers

  • Writing Apex code should be the last possible resort - use declarative tools first.
    • If 90% of what needs to be done can be done in a Flow, with the last 10% requiring a Flow, best practice is to make a Flow that does most of the work and then calls some Apex for the final 10%.

5 - Create Basic Trigger

  • To create a trigger: Dev Console > File > New Apex Trigger. “AccountTrigger”, select sObject = Account
    • Default trigger is set up to run in the context = before insert
    • system.debug is code that developers use often - it writes to the debug log.
    • system.debug(Trigger.new); - Trigger.new is the list of records being added to the database.
    • Double forward slash // creates a comment
    • command s saves on Mac, ctrl s saves on Windows
trigger AccountTrigger on Account (before insert) {
	// Display new records
    system.debug(Trigger.new);
}

6 - Trigger Types and Contexts

  • Trigger contexts: Before Insert, After Insert, Before Update, After Update, Before Delete, After Delete
    • Before Insert - IDs are not set yet
      • Can assign values to fields directly on Trigger.new. Those values will be written to the database.
    • After Insert - IDs are set
      • If updates to fields are made, would need to write another line to update values in the database.
  • Trigger.new is a list - when selecting an item we need to use [0], for example, which is the same syntax as Python. Ex: Trigger.new[0]
trigger AccountTrigger on Account (before insert) {
	// Display new records
    system.debug(Trigger.new);
    Trigger.new[0].Phone = '000-0000';
}

  • Can set up triggers to run in multiple contexts, see below.
trigger AccountTrigger on Account (before insert, before update) {
	// Display new records
    system.debug(Trigger.new);
    Trigger.new[0].Phone = '000-0000';
}

7 - Trigger Best Practices

One Trigger per object

  • If you have multiple triggers on each object, you do not have control over the order that events are executed. One trigger could execute before another.
    • Practically, this looks like one trigger that executes in all the contexts you need, with logic to determine the which functionality happens for each context.

Keep Triggers Logic-less

  • Leave logic in classes

Control triggers with declarative functionality

  • Ex: Allow admins to be able to access custom settings or custom metadata types that allow them to turn triggers on or off
    • If we have a trigger that’s messing up in Production, need to be able to have something that lets admins turn it off.
      • This is important because in Production you cannot modify code - it needs to be pushed via a change set, or metadata API, or Salesforce DX, etc.