# Write a trigger to automatically create a related Contact whenever a new Account is created.

**Topic:** Apex · **Difficulty:** Medium · **Tags:** apex-trigger, trigger, coding, scenario

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-automatically-create-a-related-contact-whenever-a-new-account-is-created

## Answer

**Basics:** A trigger is Apex code that runs automatically before or after a record is inserted, updated, deleted or undeleted. To create a child Contact you need the parent Account's Id as `Contact.AccountId`. In a `before insert` trigger the Id is still null, so you use `after insert`. Records in `Trigger.new` are read-only in after context, which is fine here because you are creating different records, not editing the Account.

**How it works:** Salesforce passes up to 200 records per chunk in `Trigger.new`. You loop over them (no SOQL or DML inside the loop), add a new `Contact` to a list for each Account, then do a single DML after the loop. Best practice is one trigger per object that delegates to a handler class, so logic is testable and ordering is controlled.

**Advanced / deep dive:** Contact's only universally required field is `LastName`, but validation rules, required custom fields, duplicate rules, and triggers or flows on Contact all run on your inserted rows and can fail them. With plain `insert`, one bad row rolls back the whole Account save. With `Database.insert(list, false)` you get partial success and a `SaveResult` per row, so you can log failures without blocking Account creation; decide deliberately which behaviour the business wants. Duplicate rules: Apex DML runs duplicate rules; "Block" rules throw errors, "Allow with alert" is bypassed in Apex unless you set `Database.DMLOptions.duplicateRuleHeader.allowSave = true`. Recursion: this trigger does not re-fire itself, but a Contact trigger that updates Accounts could loop, so guard with a static `Set<Id>` of processed Ids rather than a single static Boolean (a Boolean wrongly skips later chunks of a 10,000-row load). Person Accounts auto-create a Contact, so exclude them if enabled. Declarative alternative: a record-triggered Flow (after save, Account created) with a Create Records element; Flow is preferred for simple cases, Apex for complex logic or very high volume. Workflow Rules and Process Builder are retired and cannot create records anymore for new automations.

**Code / config example:**
```apex
// Trigger: one per object, logic delegated
trigger AccountTrigger on Account (after insert) {
    if (Trigger.isAfter && Trigger.isInsert) {
        AccountTriggerHandler.afterInsert(Trigger.new);
    }
}

public with sharing class AccountTriggerHandler {
    // Recursion guard keyed by record Id
    private static Set<Id> processed = new Set<Id>();

    public static void afterInsert(List<Account> newAccounts) {
        List<Contact> toInsert = new List<Contact>();
        for (Account a : newAccounts) {
            if (processed.contains(a.Id)) continue;
            processed.add(a.Id);
            toInsert.add(new Contact(
                AccountId = a.Id,
                LastName  = a.Name,          // LastName is required
                Description = 'Auto-created primary contact'
            ));
        }
        if (toInsert.isEmpty()) return;

        // Partial success: failures do not roll back the Account save
        Database.DMLOptions opts = new Database.DMLOptions();
        opts.DuplicateRuleHeader.allowSave = true;   // optional: bypass "alert" dup rules
        List<Database.SaveResult> results = Database.insert(toInsert, opts);
        for (Integer i = 0; i < results.size(); i++) {
            if (!results[i].isSuccess()) {
                System.debug(LoggingLevel.ERROR,
                    'Contact failed for ' + toInsert[i].AccountId + ': ' + results[i].getErrors()[0].getMessage());
            }
        }
    }
}

@IsTest
private class AccountTriggerTest {
    @IsTest static void createsOneContactPerAccount() {
        List<Account> accts = new List<Account>();
        for (Integer i = 0; i < 200; i++) accts.add(new Account(Name = 'Test ' + i));
        Test.startTest();
        insert accts;                        // bulk of 200 exercises chunking
        Test.stopTest();
        System.assertEquals(200, [SELECT COUNT() FROM Contact WHERE AccountId IN :accts]);
    }
}
```

**Hidden gotchas & must-remember points:**
- `before insert` cannot work here: the Account Id is null until after insert.
- A static Boolean recursion flag breaks bulk loads over 200 rows (multiple chunks in one transaction); use a Set of Ids.
- `Database.insert(list, false)` swallows errors unless you inspect `SaveResult`; silent failure is the classic bug.
- Apex DML does not show duplicate-alert prompts; "Allow" rules are bypassed unless a rule is set to Block.
- Contacts inserted this way are owned by the running user and count toward the 150 DML statement and 10,000 DML row limits.
- Lead conversion and Data Loader loads fire this trigger too, so test in bulk.

**Best practice:** One trigger per object, a handler class, no logic in the trigger body, and prefer a record-triggered Flow when the requirement is just "create a related record".

---
Source: ForceChallenges · last updated 2026-11-02
