Skip to main content

Apex Triggers and Classes

 Apex Triggers  is use to execute the functionality or piece of code on record manipulation ( i.e., CREATE / UPDATE / DELETE / UNDELETE  records ). A trigger executes before and after an event occurs on record.

When to use Apex Triggers ?
Apex triggers are used when we can't perform the functionality with point-n-click tool ( i,e., Workflow Rules , Process Builders ). For Ex, we need to validate a particular field before saving the record that we can't perform with validation rule as well.

Syntax for Apex Trigger :

trigger TriggerName on ObjectName (TriggerEvents1TriggerEvents2, ...) {
   
      //code goes here
      .....
      .....

}

Below are the Trigger Events :
  • Before Insert
  • After Insert
  • Before Update
  • After Update
  • Before Delete
  • After Delete
  • After Undelete

There are two different types of triggers :

  • Before Triggers :  These types of triggers are used to perform any task just before the records insertion / updation / deletion. These are mainly used to validate a record or set the to a particular field.
  • After Triggers :  These types of triggers are used when it is needed to use some information of current record that is required in some other records. For Example, ( the Record-Id is set by salesforce system after record insertion and we need to use that Record-Id in some other record we use after triggers. We may need LastModifiedById also which will be available in after triggers. )

Different types of triggers context variables :

 >   Trigger.isInsert : Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
 >   Trigger.isUpdate : Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
 >  Trigger.isDelete : Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
 >   Trigger.isUndelete : Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
 >   Trigger.isBefore : Returns true if this trigger was fired before any record was saved.
 >   Trigger.isAfter : Returns true if this trigger was fired after all records were saved.
 >   Trigger.isExecuting : Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an execute anonymous() API call.
 >   Trigger.new : Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.
 >   Trigger.newMap : A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.
 >   Trigger.old : Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.
 >   Trigger.oldMap : A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.
 >   Trigger.size: The total number of records in a trigger invocation, both old and new.

Triggers Context Variables Matrix Chart :



Examples - 1:
Below code will assign the Phone Number to contact when records are Inserted/Updated.
Trigger on Contact object :
trigger ContactTrigger on Contact (before insert, before update) {    
    if(Trigger.isBefore && ( Trigger.isInsert || Trigger.isUpdate )) {
        ContactTriggerHandler.UpdateMobileNumber(Trigger.New);
    }
}

Handler Class for trigger :
public class ContactTriggerHandler {    
    public static void UpdateMobileNumber(List<Contact> lstContact) {
        for(Contact record : lstContact) {
            record.Phone = '1234567890';
        }
    }
}
Examples - 2:
Below code will create a new contact related to the newly created Account.
Trigger on Account object :
trigger AccountTrigger on Account (after insert) {
    if(Trigger.isAfter && Trigger.isInsert) {
        AccountTriggerHandler.createContactForAccount(Trigger.New);
    }
}

Handler Class for trigger :
public class AccountTriggerHandler {
    public static void createContactForAccount(List<Account> lstAccounts) {
        List<Contact> lstContacts = new List<Contact>();
        for(Account record : lstAccounts) {
            Contact objContact = new Contact();
            objContact.FirstName = 'CorpoVision Contact';
            objContact.LastName = record.Name;
            objContact.AccountId = record.Id;
            lstContacts.add(objContact);
        }        
        if(!lstContacts.isEmpty()) {
            insert lstContacts;
        }
    }
}

By : Harshal Lad

Comments

Popular posts from this blog

OOP,s Concepts in APEX

What is OOP's Concepts in APEX Programming ?   Object-Oriented Programming System (OOPs) is a programming concept that works on the principles of abstraction , encapsulation , inheritance , and polymorphism . It allows users to create objects they want and create methods to handle those objects. The basic concept of OOPs is to create objects, re-use them throughout the program, and manipulate these objects to get results. OOP meaning “Object Oriented Programming” is a popularly known and widely used concept in modern programming languages like Java, Apex and many other. List of OOP's Concepts >  Class  :   The class is one of the Basic concepts of OOPs which is a group of similar entities. It is only a logical component and not the physical entity. Lets understand this one of the OOPs Concepts with example, if you had a class called “Expensive Cars” it coul...

Polymorphism in Apex

Polymorphism in Apex P olymorphism in simple word can be said as  One name many forms. For example , a man can play a role as an Employee, as a Father or as a Husband in his day-to-day life. It means that he can be in any of these form.  Polymorphism can be achieved by these two ways : Method Overloading Method Overriding Method Overloading If a class have multiple methods with same name but different parameters (either different length of the arguments or different data types of the arguments), it is known as Method Overloading. If we have to perform only one operation, with the same name of the methods increases the readability of the program as well as its very logical too. Let’s suppose if we want to perform addition of the given numbers but there can be any number in arguments as below: Example of method over...