Monday, October 28, 2019

WHAT IS AFTER INSERT EVENT IN APEX TRIGGER, EXPLAIN IT WITH AN EXAMPLE?


AFTER INSERT:

This event runs the block of code after inserting data into the database. Operations such as creating or updating related records can be performed under this event.

SYNTAX:

trigger triggerName on objectName (after insert) {
   // Block of code
}

SCENARIO:

We are having the requirement to insert dummy Contact record as a related object on Account when the Account record is created.

APEX TRIGGER:
trigger AccountMainTrigger on Account (after insert) {// Specifying the event.
    createContactClass obj=new createContactClass(); // Declaring instance of the class.
    if(trigger.isafter && trigger.isinsert) // Using context variables.
    {
     obj.method1(trigger.new); // Calling apex class method.
    }
}

APEX CLASS:

 public class createContactClass {
    List<contact> conList=new List<contact>();
    public void method1(List<Account> accountList){ // Obtaining the list of Account records from trigger.new.
        for(Account obj:accountList){ // Iterating over account list.
            contact con=new contact(); // Creating a contact instance.
            con.FirstName='Testing contact';  // Creating contact record for each account
            con.LastName='Last Name';
            con.AccountId=obj.id; // Mapping contact torespective Account.
            conList.add(con); // Adding all contact in List. We should always perform DML operations on the collection of records to avoid hitting governor limit.
        }
        if(conList.size() > 0){ // Checking if the list has records.
            insert conList; // Inserting contact list.This is how we should perform DML operations on the collection of records.
        }
    }
}




after insert and after update trigger in salesforce example
trigger scenarios in salesforce


6 comments:

  1. will trigger.new works for after triggers??

    ReplyDelete
    Replies
    1. i dont think it works. because there is no trigger.new records as the record is already ineterted. trigger.new works only before triggers.Please correct the code.

      Delete
    2. Please refer https://www.sfdc-lightning.com/2019/10/availability-of-trigger.new-trigger.old-in-apex-trigger.html

      Delete
    3. This is basically used to create child records after parent record is inserted.

      Delete