Activity Forums Salesforce Discussions How to determine whether to use After or before in Salesforce trigger?

  • How to determine whether to use After or before in Salesforce trigger?

  • PRANAV

    Member
    August 2, 2016 at 12:59 pm

    Hi All,

    How to determine whether to use After or before in trigger?

    Thanks

  • Himanshu

    Member
    August 2, 2016 at 1:29 pm

    Hi Pranav,

    Before Trigger:-

    I'm updating the record that's being updated/inserted - or doing something based on the record being modified
    Examples: Set value of a pick list based on criteria. Send apex e-mail based on the record updated/inserted.

    After Trigger:-

    I'm updating or creating records that are NOT being updated/inserted
    Examples: Create a task of an Opportunity that's been edited, Change a look up value on a related record from the Opportunity being edited
    The main thing to consider is that the Before happens before the data has been written to the server. This means you can modify the records in "Trigger.new" without having to call a separate "Update." This is ideal if you want to modify data in the records within Trigger.new

    After happens after the data has been written to the server. This is important when wanting to create additional related records (Can't create a related record until AFTER the parent has been inserted).

  • Avnish Yadav

    Member
    September 29, 2018 at 8:52 pm

    Hello,

    Before Trigger: In case of validation check in the same object

    After Trigger: Insert/Update related object, not the same object

    Thanks.

  • William

    Member
    December 14, 2018 at 4:41 am

    1.        "before" triggers to validate data or update fields on the same record being triggered.

    2.        "after" triggers to update parent or related records

    3.        "insert" for events that occur on record creation

    4.        "update" for events on existing records

    BEFORE trigger

    1.      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.

    2.      In case of validation check in the same object.

    3.      Insert or update the same object.

    AFTER trigger

    1.      AFTER triggers are usually used when information needs to be updated in a separate table due to a change.

    2.      They run after changes have been made to the database (not necessarily committed).

    3.      Insert/Update related object, not the same object.

    4.      Notification email.

    5.      We cannot use After trigger if we want to update a record because it causes read-only error. This is because after inserting or updating, we cannot update a record.

Viewing 1 - 4 of 4 posts

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos