Unlocking the Power of Custom Metadata Types in Apex: Dynamic, Declarative, and Secure


Salesforce’s Custom Metadata Types (CMDT) are a game-changer for building flexible, maintainable, and secure applications. If you’re still hardcoding configuration values or feature toggles in Apex, it’s time to level up! In this post, we’ll explore how to leverage Custom Metadata Types in your Apex code to drive dynamic behavior and make your solutions more AppExchange-friendly.


Why Custom Metadata?

  • Declarative Configuration: Admins can manage settings without deploying code.
  • Packaging Ready: CMDT records can be included in managed packages.
  • SOQL Accessible: Query in Apex just like custom objects, but without governor limitations on counts.
  • Secure: Supports metadata-level security, separate from runtime data.

Step 1: Define a Custom Metadata Type

Let’s create a CMDT called Feature_Toggle__mdt with fields:

  • Feature_Name__c (Text)
  • Is_Enabled__c (Checkbox)

You can do this in Setup → Custom Metadata Types → New Custom Metadata Type.


Step 2: Populate Metadata Records

Create records like:

LabelFeature_Name__cIs_Enabled__c
Enable New Flownew_flowtrue
Show Beta Buttonbeta_buttonfalse

Step 3: Query Custom Metadata in Apex

public class FeatureToggleUtil {
    public static Boolean isFeatureEnabled(String featureAPIName) {
        Feature_Toggle__mdt toggle = [
            SELECT Is_Enabled__c 
            FROM Feature_Toggle__mdt 
            WHERE Feature_Name__c = :featureAPIName
            LIMIT 1
        ];
        return toggle != null && toggle.Is_Enabled__c;
    }
}

Step 4: Use Feature Toggles in Your Business Logic

if (FeatureToggleUtil.isFeatureEnabled('new_flow')) {
    // Run the new flow logic
} else {
    // Fallback or legacy logic
}

Step 5: Secure, Deploy, and Empower Admins

  • Security: No FLS or CRUD required for CMDT; accessible in all Apex contexts.
  • Deployment: CMDT records are packageable and deployable across orgs.
  • Empower Admins: Admins can control features without asking devs for redeployment!

Bonus: Bulk Query and Caching Example

public class FeatureToggleCache {
    private static Map<String, Boolean> cache;
    public static Boolean isFeatureEnabled(String featureAPIName) {
        if (cache == null) {
            cache = new Map<String, Boolean>();
            for (Feature_Toggle__mdt m : [SELECT Feature_Name__c, Is_Enabled__c FROM Feature_Toggle__mdt]) {
                cache.put(m.Feature_Name__c, m.Is_Enabled__c);
            }
        }
        return cache.containsKey(featureAPIName) ? cache.get(featureAPIName) : false;
    }
}

Conclusion

Custom Metadata Types are a must for every serious Salesforce developer. They help you build dynamic, configurable, and secure solutions that are easy to manage and ready for AppExchange. Start replacing those hardcoded values today!


Happy coding! ðŸš€

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post