Sub topic 2
Duplicate Rules Through Parent Saves
Assume you know basic Apex triggers, Salesforce objects, Flow, validation rules, and DML. This chapter follows the save sequence after custom validation and before commit.
Duplicate rules can block the save
Duplicate rules compare the incoming record with existing records. A rule can warn the user or block the operation. A blocked insert or update raises a DML error, so the transaction does not continue to after triggers.
The database save is not the commit
If duplicate checks pass, Salesforce saves the record to the database without committing the transaction. The record has a database Id, but other automation can still fail. If any unhandled error occurs before commit, Salesforce rolls back the transaction, including related records created earlier in the transaction.
After triggers can use the Id
After triggers run after the record has been saved. Trigger.new is read-only, so use after triggers for related records or work that requires the saved record's Id.
trigger AccountFollowUp on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account accountRecord : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up',
WhatId = accountRecord.Id
));
}
insert tasks;
}Before insert has no Id. In a before trigger, change fields directly on Trigger.new without issuing another update.
Post-save automation
After triggers are followed by assignment rules, auto-response rules, workflow rules, escalation rules, and entitlement rules when their conditions apply. These features can update records or create additional work. Their actions still belong to the same transaction unless they explicitly run asynchronously.
Workflow updates can re-fire triggers
If a workflow field update changes the record, Salesforce performs another update cycle. The record's before update and after update triggers can run again. This can produce recursion or duplicate related records. A static set of processed record Ids can prevent repeated work during one transaction.
> Callout note > A successful after trigger does not prove that the save will commit. Later automation can still fail and roll back the complete transaction.
Flows and roll-up summaries
After-save record-triggered flows run after the record-save automation described above. A roll-up summary recalculates a value on a parent record. Saving that parent can invoke automation on the parent, adding work and governor-limit usage to the transaction.
Exercise
Why should an after insert trigger create related records in one bulk DML statement?
Show answer
The record Id is available after insert, and one statement handles all records while using fewer DML operations.