22/04/2013
When to use Before-Triggers
Before-trigger events occur before a record’s changes are committed to the database. This particular event is ideal for performing data validation, setting default values, or performing additional logic and/or calculations. Please keep in mind that in the case of before-insert events, because the event is executed before the record is committed to the database it will not have a record id.
Before-triggers in my opinion are the most efficient and are going to be your goto method for most of the triggers you will write for a couple of reasons. The first being that you can perform data validation and reject a record before it is committed to the database, meaning there is no cost to performance by the system having to roll back an update. Second, you can update fields or set default values for a record without having to initiate another DML command.
For example the code below illustrates setting a default value on a record. No DML required.
trigger setDefaultAccountValues on Account (before insert, before update) {
for (Account oAccount : trigger.new) {
oAccount.Industry = ‘Cloud Computing’;
}
}
When to use After-Triggers:
==================
After-trigger events occur after a record has been committed to the database, which means that records being inserted will have a record id available. This particular event is ideal for working with data that is external to the record itself such as referenced objects or creating records based on information from the triggered object.
For example the code below illustrates creating an Opportunity after an Account is created.
trigger createNewAccountOpportunity on Account (after insert) {
List listOpportunities = new List();
for (Account oAccount : trigger.new) {
Opportunity oOpportunity = new Opportunity();
oOpportunity.Name = oAccount.Name;
oOpportunity.AccountId = oAccount.Id;
oOpportunity.Stage = ‘Proposal’;
oOpportunity.CloseDate = System.today() + 30; //Closes 30 days from today
listOpportunities.add(oOpportunity);
}
if (listOpportunities.isEmpty() == false) {
Database.update(listOpportunities);
}
}