ApexSensei

Drills › Automate with triggers

Create follow-up Tasks after Contact insert

Automate with triggers · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path

Scenario. Sales reps want a follow-up activity as soon as an imported Contact is saved.

Build one related Task per new Contact in an after-insert handler and insert them all with one DML statement.

What you will learn

Use after insert when related records need the new records' Ids. Records get their Ids only when they save. Build the related records in a loop, then insert the whole list once.

List<Note> notes = new List<Note>();
for (Account row : accounts) {
    notes.add(new Note(ParentId = row.Id, Title = 'Hi'));
}
insert notes;

Gotcha. An insert inside the loop runs once per record and hits the 150-DML limit on a big import.

The task

Complete the handler so every new Contact gets one follow-up Task, and all Tasks save with a single insert.

Examples:

  • Contact Ng → Task with Subject Welcome Ng, Priority High, linked to that Contact
  • two Contacts → two Tasks, one per Contact
  • 200 Contacts → 200 Tasks, still with one Task insert

Requirements:

  1. Loop over every Contact the trigger passes in.
  2. Build one Task per Contact with WhoId set to that Contact's Id.
  3. Set Subject to Welcome plus the Contact's LastName, and Priority to High.
  4. Add the Tasks to a list and insert the list once, after the loop.

Starter code

public class AS_B9B475322DF3_ContactTasks {
    public static void afterInsert(List<Contact> contacts) {
        List<Task> followUps = new List<Task>();

        for (Contact contact : contacts) {
        }

        if (!followUps.isEmpty()) {
        }
    }
}

When it passes

Each new Contact gets exactly one high-priority Task with the right Subject, and 200 Contacts cost the same number of DML statements as 2.

Try this drill free

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

‹ Write your first before-insert trigger · React to a Contact email change ›