1.

When Do You Use A Before Vs. After Trigger?

Answer»

95% of triggers are before triggers – so if you’re unsure, go with before!

You may be wondering why so many triggers are before triggers. There’s a GOOD reason – they’re simpler to USE. If you need to make any changes to a record entering your after trigger, you have to do a DML STATEMENT. This isn’t necessary in a before trigger – changes to records entering your trigger always save!

The specific use case of an after trigger is when you need to associate any record to a record being created in your trigger. Here’s an example:

// AUTOMATICALLY create an Opp when an Account is created
trigger AutoOpp on Account(after insert) {
List<Opportunity&GT; newOpps = new List<Opportunity>();
for (Account acc : Trigger.new) {
Opportunity opp = new Opportunity();
opp.Name = acc.Name + ' Opportunity';
opp.StageName = 'Prospecting';
opp.CloseDate = Date.today() + 90;
opp.AccountId = acc.Id; // Use the trigger record's ID
newOpps.add(opp);
}
insert newOpps;
}

95% of triggers are before triggers – so if you’re unsure, go with before!

You may be wondering why so many triggers are before triggers. There’s a good reason – they’re simpler to use. If you need to make any changes to a record entering your after trigger, you have to do a DML statement. This isn’t necessary in a before trigger – changes to records entering your trigger always save!

The specific use case of an after trigger is when you need to associate any record to a record being created in your trigger. Here’s an example:

// Automatically create an Opp when an Account is created
trigger AutoOpp on Account(after insert) {
List<Opportunity> newOpps = new List<Opportunity>();
for (Account acc : Trigger.new) {
Opportunity opp = new Opportunity();
opp.Name = acc.Name + ' Opportunity';
opp.StageName = 'Prospecting';
opp.CloseDate = Date.today() + 90;
opp.AccountId = acc.Id; // Use the trigger record's ID
newOpps.add(opp);
}
insert newOpps;
}



Discussion

No Comment Found