function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Trigger Before Insert - Stopping the data from saving

How do you prevent the data from saving on a trigger that is set to before insert?
To prevent data from saving during a before insert trigger, add an error. This sample code is taken from the Introduction to Apex:

trigger myAccountTrigger on Account (before insert, before update) { 
  if (Trigger.isInsert) {
  if (Trigger.isUpdate) {
    for(Account a:
      if ( == 'bad')'Bad name'); // prevent update


David @ ConfigeroDavid @ Configero
You can do validation rules declaratively or programmatically. As previously mentioned if you call .addError(message) on a record or a record's field, then it will add that validation error and throw an error forcing that record to fail.  In most (general) cases, if this is run with the insert/update failing upon a single error, this validation will cause the whole transaction to roll back.  For example if 200 Accounts were updated, make sure this will cause the expected behavior you are looking for.