ApexSensei

Drills › Automate with triggers

Write your first before-insert trigger

Automate with triggers · Beginner · 10 min · Runs in your Salesforce Developer org · Apex Path

Scenario. Contacts arrive from an import. Some have no Description, and the team wants a clear default without losing text that other systems send.

Loop over Trigger.new in a before-insert trigger and give blank Contact descriptions a default, with no DML.

What you will learn

A trigger runs when records save. In a before insert trigger, Trigger.new is the list of records about to be saved. Change their fields directly. Salesforce saves your changes, so you need no insert or update.

for (Contact row : Trigger.new) {
    row.Title = 'Imported';
}

Gotcha. One insert can send up to 200 records to your trigger. Loop over all of Trigger.new, not just Trigger.new[0].

The task

Write the body of the Contact trigger so every new Contact with a blank Description gets New contact before it saves.

Examples:

  • Description not set → New contact
  • Description Imported → stays Imported
  • one insert with a blank first Contact and a filled second → the blank one gets New contact, the filled one keeps its text

Requirements:

  1. Keep the before insert event that the starter declares.
  2. Loop over every Contact in Trigger.new.
  3. Use String.isBlank when you decide (it covers null, empty and text with only spaces, so you never need a second check).
  4. Leave a Description that already has text alone.
  5. Do not call insert or update. A before trigger saves your changes for you.

Starter code

trigger AS_8AF8EF0B5878_ContactBefore on Contact (before insert) {
}

When it passes

Every new Contact with a blank Description saves as `New contact`, filled Descriptions stay as they are, and a 200-record insert works with no extra DML.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

Create follow-up Tasks after Contact insert ›