Skip to main content
Loading...

Dynamic Code Execution

Abstract illustration of Salesforce automation toggles controlling Apex execution

Configurable control is hard to come by in Salesforce production. Changing code usually means a deployment—and often a second one to reverse the change. That is a lot of ceremony for testing, debugging, or reproducing an issue, especially when code coverage is in the way.

A common workaround is a custom setting with a checkbox per object to disable triggers. It works until you need another object (another field) or want the same control for Aura-enabled methods, invocable Apex, REST endpoints, or shared utilities.

This approach keeps the same idea and makes it scalable with Custom Metadata.

Problem statement

  • Data migration teams often need automation off after code is already in production. Disabling triggers the usual way means deploying inactive triggers, then deploying them active again.
  • Teams need a simple switch for any trigger, class, or individual method—not only object-level triggers.

Solution

Use a Custom Metadata Type instead of one checkbox field per object:

Field Purpose
Apex_Class_Trigger_Name__c Apex trigger or class name
Method_Name__c Optional. Blank disables the whole trigger/class; set a method name to target only that method
Disable_Execution__c Check to block execution
Description__c Optional notes

Sample records

Sample Dynamic Code Execution metadata records

Examples

Example usage of Dynamic Code Execution
Another Dynamic Code Execution example

Resources

  • Apex: DynamicCodeExecution, DynamicCodeExecution_Test
  • Custom Metadata: Dynamic_Code_Execution__mdt
  • Seed record: DO_NOT_DELETE (supports test coverage)
  • List view: All

Pre-deployment steps

  • Back up the target org.
  • Confirm these resources are not already present; if they are, merge instead of overwriting.

Deployment steps

Source: dynamic-code-execution

Post-deployment steps

Call the utility from triggers, classes, and methods:

  • Class: DynamicCodeExecution
  • Method: allowExecution(String) → true when allowed, false when disabled
// Entire trigger
DynamicCodeExecution.allowExecution('AccountTrigger');

// One method
DynamicCodeExecution.allowExecution('AccountTriggerHandler.updateContactOwner');