Tuesday, 15 July 2014

Trigger.isExecuting Usage in Salesforce


In brief Trigger.isExecuting determines if the context is trigger or Visualforce. If it returns true context is trigger otherwise context is Visualforce or other. In your case Trigger.isExecuting will return true.
Apex Class
  1. public class TriggerContextDemo
  2. {
  3.   public Boolean updateContact(Contact[] conList)
  4.   {
  5.      // Will not update contact if method is called in TriggerContext
  6.      if(Trigger.isExecuting)
  7.      {
  8.         // Do Not Update Any contact
  9.         System.debug(' $ $ NOT updating contacts');
  10.      }
  11.      else
  12.      {
  13.        // update contacts
  14.        System.debug(' $ $ updating contacts');
  15.      }
  16.      System.debug(' $ $ return ' + Trigger.isExecuting);
  17.      return Trigger.isExecuting;
  18.   }
  19. }

Apex Trigger on Contact object

  1. trigger ContextCheckTrigger on Contact (before insert, before update)
  2. {
  3.    TriggerContextDemo demo = new TriggerContextDemo();
  4.    demo.updateContact(Trigger.New);
  5. }

Now if any of Contact's record is updated or inserted by Visualforce Controller or manually it will fire a trigger and in the trigger instance method of TriggerContextDemo is called and result in System.debugs:

$ $ NOT updating contacts // Because Trigger.isExecuting is true

$ $ return true // Trigger Context exist


If we call the same class from Developer console's execute Anonymous like this:

TriggerContextDemo cc = new TriggerContextDemo();
cc.updateContact(null);
In this case same class will result in system.debugs:

$ $ updating contacts

$ $ return false // No trigger context



Thanks to StackExchange Community

3 comments:

  1. it was really a nice article and i was really impressed by reading this
    article We are also giving Linux Course Online Training.the Linux-
    -Online-Training
    is the one of the best Online Training institute.

    ReplyDelete
  2. Hi Guys, I have all latest dumps of salesforce certification (Summer ‘17) if anyone wants you can mail me at
    sfdcconsultant25@gmail.com

    These are original questions from the certification exam and very useful to pass the exam.
    Above 90% questions come from it
    I have all latest dumps of following exams

    Salesforce Administrator (ADM 201)
    Salesforce Sales Cloud Consultant (CON 201)
    Salesforce Service Cloud Consultant
    Platform Developer I
    App Builder and App builder transition exam

    Good Day!

    ReplyDelete
  3. Bangladesh Primary Education Board PSC Result 2019 With Marksheet

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...