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

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...