Activity › Forums › Salesforce® Discussions › What is the difference between before and after trigger in Salesforce?
-
What is the difference between before and after trigger in Salesforce?
Posted by Laveena on August 22, 2019 at 5:10 AMWhat is the difference between before and after trigger in Salesforce?
Sumit kumar replied 6 years, 3 months ago 6 Members · 5 Replies -
5 Replies
-
Hi,
Before triggers are used to update or validate record values before they’re saved to the database. 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 effect changes in other records.
For more info visit :
- [adinserter block='9']
-
BEFORE triggers are usually used when validation needs to take place before accepting the change. They run before any change is made to the database. Let’s say you run a database for a bank. You have a table accounts and a table transactions. If a user makes a withdrawal from his account, you would want to make sure that the user has enough credits in his account for his withdrawal. The BEFORE trigger will allow to do that and prevent the row from being inserted in transactions if the balance in accounts is not enough.
AFTER triggers are usually used when information needs to be updated in a separate table due to a change. They run after changes have been made to the database (not necessarily committed). Let’s go back to our back example. After a successful transaction, you would want the balance to be updated in the accounts table. An AFTER trigger will allow you to do exactly that.
-
Before Trigger : It is used for update or validate record values before they’re saved to the database. In this, Database saves the records that fired the before trigger after the trigger finishes execution. If you want to update and delete a record in before trigger , it will give you a runtime error.
Example :
trigger sampleTrigger on Account (before insert) {
for(Account a : Trigger.New) {
a.Fax = ‘New Fax’; } }
It updates the Fax field for each account in a for loop.
After Trigger : It can be used to access field values that are set by the database. We can’t use After trigger if we want to update a record because it causes a read-only error. if you want to delete the database in after trigger , it will give the runtime error.
-
Before triggers are used to update or validate record values before they’re saved to the database. 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 effect changes in other records. The records that fire the after trigger are read-only
Log In to reply.