Activity Forums Salesforce® Discussions What is the difference between before and after trigger in Salesforce?

  • Hariom Chaudhary

    Member
    August 22, 2019 at 5:11 am

    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 :

    https://salesforce.stackexchange.com/questions/96263/what-is-the-exact-difference-between-before-update-and-after-update-trigger

     

  • Arun

    Member
    January 20, 2020 at 9:54 am

    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.

  • Shweta

    Member
    January 22, 2020 at 2:32 pm

    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.

  • Sumit

    Member
    January 29, 2020 at 11:55 am

    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.

Popular Salesforce Blogs