[SalesForce] Trigger.isExecuting value from Apex Class

As per the documentation, trigger.isExecuting returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.

I am a bit confused by this. If VF page calls a controller function which makes an DML operation firing the trigger, what would be the value of isExecuting in that case?

Best Answer

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.

Simple ex:

Create a class:

public class TriggerContextDemo
{
  public Boolean updateContact(Contact[] conList)
  {
     // Will not update contact if method is called in TriggerContext
     if(Trigger.isExecuting)
     {
        // Do Not Update Any contact
        System.debug(' $ $ NOT updating contacts');
     }
     else
     {
       // update contacts
       System.debug(' $ $ updating contacts');
     }
     System.debug(' $ $ return ' + Trigger.isExecuting);
     return Trigger.isExecuting;
  }
}

Now Create a trigger on Contact

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

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

Related Topic