• When To Use Before Triggers & After Triggers in Salesforce

    Published By: Venu Gutta
    Published on: Wednesday 22 February 2017
    A- A+
    Difference Between Before Trigger and After Trigger & When Should we use Before & After Triggers:

    Before Triggers: Before triggers are used to update or validate record values before they’re saved to the database.

    Uses:

    1. When we need to write validation on same object record.
    2. Insert and update operation same object.

    Sample Example: if opportunity amount is less then 10000 then through error.


    Trigger validateOppRecord on opportunity(Before Insert){
                             For(opportunity o: Trigger.new)
                               If(o.amount<10000){
                                   o.addError(‘please Enter opportunity amount more than 5000’);
                                  }

                            }

    After Triggers: 
    After Trigger:  After trigger is used when we perform DML operation on one object record and action will effect on another object record by accessing system fields such as record id and last mododifieddate field .

    USES: Insert/Update on related object, not the same object.
                 Notification email.


    Note: We cannot use After trigger if we want to update same record because after saving, record will be committed to database and record will be locked. The records, which fired with after trigger are read only. so  it causes read only error(System.FinalException: Record is read-only) if we perform operation on same object.

    Sample Example: Automatically create a Contact record when we create new Account Record.

    Trigger autoaccCon on Accout(After Insert){
        List<Contact> conlist = new List<Contact>();
        For(Account acc:Trigger.New){
           Contact con = New Contact();
           con.accountid=acc.id;
           con.lastname = acc.name;
           conlist.add(con);
        }
        insert conlist;
    }