Activity Forums Salesforce® Discussions How can we write a trigger for before and after DML operation? Reply To: How can we write a trigger for before and after DML operation?

  • shariq

    Member
    August 7, 2017 at 12:52 pm

    Hi Mohit,

    Before triggers can be used to update or validate record values before they are saved to the database.

    After triggers can be used to access field values that are set by the database (such as a record's Id or lastUpdated field) and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.

    Use Before Trigger:
    In the case of validation check in the same object.
    Insert or update the same object.

    Use After Trigger:
    Insert/Update related object, not the same object.
    Notification email.
    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.

    trigger AccountTrigger on Account (before insert, after insert)
    {
    if(Trigger.isBefore)
    {
    if(Trigger.IsInsert)
    {
    Contact cont = new Contact();
    cont.LastName = Trigger.new[0].name;
    cont.FirstName = Trigger.new[0].name;
    insert cont;
    }
    else if(Trigger.IsInsert&&Trigger.IsAfter)
    {
    Contact cont = new Contact();
    cont.LastName = '(Updated)';
    cont.FirstName = Trigger.new[0].name+ 'Updated';
    insert cont;
    }
    }
    }