Usage of before triggers
- johnsontitus
- May 14, 2020
- 1 min read
Before triggers are used to update or validate record values before they’re saved to the database.
Use Case: Every time an account is inserted, validate whether its name is 'bad' its type should be updated to 'Prospect'.
trigger trgAccountB4Ins on Account (before insert) { // is only available in insert, update,
// and undelete triggers, and the records can only be modified in before triggers. for(Account a : Trigger.New){ //validate if(a.name == 'bad'){ a.name.addError('Bad name'); } //update if it passes validation else{ a.Type = 'Prospect'; } } }
After triggers are used to access field values that are set by the system (such as a record's Id or LastModifiedDate field), and to affect changes in other records.
The records that fire the after trigger are read-only.
Use Case: Every time a new account is created, create a new opportunity record that
associates to the new account.
trigger trgAccountAftIns on Account (after insert) { Opportunity ops = new Opportunity(); for(Account act : Trigger.New){ ops.Name = 'New Opportunity'; ops.StageName = 'Prospecting'; ops.AccountId = act.Id; } insert ops; }

Comments