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

Salesforce Development Index

C ourse C ontent Declarative Features Vs Programmatic Features Salesforce Architecture ( MVC ) Data Types Apex Classes If – Conditional and loops Collections in APEX List Set Map Oops Concepts Inheritance Polymorphism Encapsulation Abstraction Data Manipulation Language (SOQL) & SOSL Exception Handling Triggers and its Best Practices Custom Setting, Custom Metadata and Custom Labels Where to use it ? How to use it ? Apex Trigger + Custom Setting Asynchronous Apex Batch Classes Scheduler Classes Queueable Classes Future Method Apex Governor Limits Test Classes for Triggers and Apex classes Visualforce Pages Standard Controllers Extension Controllers Custom Controllers Wrappers Classes in Apex By : Harshal Lad ( CorpoVision Te...

Opportunities at Paidwork Company

Unveiling the Potential of Paidwork Company : Unlocking Earning Methods, Referral Programs, and Achievements In the ever-evolving landscape of remote work and freelancing, Paidwork has emerged as a noteworthy platform that not only offers a diverse range of earning methods but also provides users with unique opportunities for growth and recognition. This article will delve into the intricacies of Paidwork, exploring its earning methods, referral program, and the benefits of achieving milestones on the platform. Go to Paidwork Website 1. Earning Methods on Paidwork: Paidwork provides freelancers and remote workers with various avenues to earn money, catering to a wide range of skills and expertise. The primary earning methods on Paidwork include: a. Freelance Projects: Users can browse through a plethora of freelance projects posted on Paidwork. From graphic design and content creation to software development and digital marketing, the platform hosts diverse opportunities for indi...