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.
- 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.
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.
Create records like:
Label | Feature_Name__c | Is_Enabled__c |
---|---|---|
Enable New Flow | new_flow | true |
Show Beta Button | beta_button | false |
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;
}
}
if (FeatureToggleUtil.isFeatureEnabled('new_flow')) {
// Run the new flow logic
} else {
// Fallback or legacy logic
}
- 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!
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;
}
}
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! 🚀
Post a Comment