Development questions

How do addError() methods work inside triggers, and can they be applied to specific fields?

DevelopmentMediumTCSDeloitteCapgemini

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.old records.
  • 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