Showing posts with label Apex Trigger After Insert Explained. Show all posts
Showing posts with label Apex Trigger After Insert Explained. Show all posts

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 Event in Apex Trigger
After Insert Event in Apex Trigger