Development questions
How do addError() methods work inside triggers, and can they be applied to specific fields?
addError(String msg) marks a record (or a field) as failed with a custom message and blocks that record's save.
- Record level:
acc.addError('Cannot save');shown at top of page. - Field level:
acc.Phone.addError('Phone is invalid');shown next to the field. - In delete triggers use it on
Trigger.oldrecords. - In bulk operations with
allOrNone=false, only the flagged records fail; with the default, the whole DML rolls back. - Use
addError(msg, false)to disable HTML escaping only when the message is trusted.
It is typically used in before triggers for validations.
apex-triggertriggervalidation
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?