Sub topic 1
What Custom Metadata Types Are and Why Use Them
Apex code often depends on values that change over time. Examples are a discount threshold, a feature toggle, an endpoint name, or the Apex class that handles a region. If you hardcode these values, every change means editing code, running tests, and deploying. Custom metadata types move those values out of the code and into records that you deploy and manage like other configuration.
This chapter covers what a custom metadata type is, how its records differ from ordinary data, and when it is the right place to keep configuration. Later chapters cover creating types, reading them in detail, and the more advanced patterns.
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax: classes, methods, collections, and SOQL.
- Salesforce Setup, custom objects, and custom fields.
- Apex unit tests and the
@IsTestannotation. - That Salesforce orgs include sandboxes, and that changes move between orgs through deployments.
The problem: configuration buried in code
Look at this method. The tier thresholds and percentages are written directly into the logic.
public with sharing class DiscountCalculator {
public static Decimal percentFor(Decimal orderTotal) {
if (orderTotal >= 1000) {
return 15;
} else if (orderTotal >= 500) {
return 10;
} else if (orderTotal >= 100) {
return 5;
}
return 0;
}
}Now the business asks for the 500 threshold to become 400, but only after testing in a sandbox. The change requires a developer, a code edit, a deployment, and a test run. The same applies to every other value like it. A developer is needed for what is really a settings change.
Hardcoded values cause other problems too:
- The values are repeated across classes, triggers, and flows, so they drift apart.
- Sandboxes and production cannot differ without branching the code.
- Administrators cannot see or review the values without reading Apex.
What a custom metadata type is
A custom metadata type is a definition, similar to a custom object, whose records describe the configuration of your application. You define the type and its fields once. Each record of that type holds one set of configuration values.
Four properties set it apart:
- The records are metadata, not data. They are components that you retrieve, deploy, and package, the same way you handle an Apex class or a custom field. They are not rows that you load with a data tool.
- The type name ends in
__mdt. A type labeled "Feature Flag" has the API nameFeature_Flag__mdt. You use this name in Apex and SOQL. Fields you add end in__c, as on custom objects. - Apex reads the records without a query in most cases. The static methods
getInstance()andgetAll()return records directly, and they do not count against the SOQL query limit. SOQL is also supported when you need to filter or sort. - Apex cannot change the records with DML.
insert,update, anddeleteare not available on custom metadata records. Changes come from Setup, from a deployment, or from the Metadata API.
Each record has a label, a human-readable name. It also has a developer name, a unique API identifier that you use when you look the record up in code. Both are part of every custom metadata type, in addition to the fields you define.
How configuration reaches your code
The diagram shows where custom metadata records come from and how Apex uses them.
Because the records arrive by deployment, they travel with the code that depends on them. If a class needs a feature flag record to exist, you deploy the record in the same change set or source-control commit as the class. That keeps the sandbox, the test org, and production consistent.
A first example: a feature flag
Suppose you create a type named Feature_Flag__mdt with one checkbox field, Is_Enabled__c. Each record in this type represents one flag, and its developer name is the flag name. The next chapters show how to create the type and the records. For now, focus on how little code the reading side needs.
public with sharing class FeatureFlags {
public static Boolean isEnabled(String flagName) {
Feature_Flag__mdt flag = Feature_Flag__mdt.getInstance(flagName);
return flag != null && flag.Is_Enabled__c;
}
}getInstance() returns the record whose developer name matches the argument, or null if no such record exists. The flag != null check means a missing flag counts as disabled, which is usually the safe default.
A caller can then branch on the flag:
if (FeatureFlags.isEnabled('New_Checkout')) {
// new behavior
} else {
// existing behavior
}An administrator can turn New_Checkout on in a sandbox, check it, and then deploy the changed record to production. No Apex changes.
Why not just use a custom object?
You could store settings in an ordinary custom object. Custom metadata types have properties that a custom object lacks.
| Concern | Hardcoded in Apex | Custom object records | Custom metadata records |
|---|---|---|---|
| Changed without editing code | No | Yes | Yes |
| Moves with a deployment | With the code | No, data must be loaded separately | Yes |
| Readable without a SOQL query | Not applicable | No | Yes, with `getInstance()` and `getAll()` |
| Editable with DML in Apex | Not applicable | Yes | No |
| Same values in every org after deploy | Yes | Only if you load them | Yes |
The deployability is the key difference. Records in a custom object are data. When you refresh a sandbox you get a copy of data, and when you deploy code to production the configuration rows are not included. Teams then maintain a data-load script, or forget it and see the code fail in production. Custom metadata records avoid this because they are deployed with the code.
The cost is that you cannot write to them from Apex in the usual way. That makes custom metadata suited to configuration that changes at deployment time or by an administrator, not to values that your code updates at run time, such as a counter or the time of the last sync. Chapter "Choosing between custom metadata, custom settings, and custom labels" compares the options in detail.
What belongs in custom metadata
Good candidates are values that describe how the application should behave:
- Feature flags that switch behavior on or off.
- Thresholds, tiers, and rates, such as the discount rules above.
- Mappings, for example a region code mapped to a tax rule or an integration endpoint name.
- Strategy selection, where a record names the Apex class to use for a case.
- Per-environment settings that differ between sandbox and production.
Poor candidates are values your code changes while running, and large amounts of business data. Custom metadata has a size limit per namespace, and it is not meant to hold records that users create daily.
What changes in your design
Using custom metadata shifts how you structure code. Three habits follow from it.
First, keep the lookup in one place. The FeatureFlags class above is the only code that knows the type is called Feature_Flag__mdt and that the checkbox is Is_Enabled__c. Callers ask a question and get an answer. If the type changes later, one class changes.
Second, decide what a missing record means. getInstance() returns null when the developer name is not found, so every caller must handle that case. The flag example treats it as disabled. For a tax strategy, a missing record may be an error that should throw an exception. Choose deliberately, and write it down in the method that does the lookup.
Third, treat the developer name as part of your contract. Code that calls getInstance('New_Checkout') depends on a record with exactly that developer name existing in every org where the code runs. If the record is not deployed, the code silently takes the null path. Always deploy the record together with the code that reads it.
Summary of the model
- A custom metadata type defines the shape of configuration. Its records hold the values.
- Records are metadata, so they deploy and package with your code.
- Apex reads them with
getInstance(),getAll(), or SOQL, and cannot use DML on them. - They fit configuration that changes by deployment or by an administrator, and they do not fit values your code updates at run time.
Exercises
Exercise
A team stores discount tiers in a custom object. After a production deployment, the discount code returns 0 for every order, although it worked in the sandbox. What is the likely cause, and how would custom metadata types prevent it?
Show answer
The tier records are data, not metadata, so they were not part of the deployment. Production has the new code but none of the tier rows, and the lookup finds nothing. If the tiers were custom metadata records, they would be deployed together with the code, so production would have the same records as the sandbox.
Exercise
You call FeatureFlagmdt.getInstance('BetaSearch') in an org where no record has the developer name Beta_Search. What does the call return, and how should isEnabled() handle it?
Show answer
It returns null. isEnabled() should check for null before reading IsEnabledc, as in "return flag != null && flag.IsEnabled__c;", so that a missing flag is treated as disabled and no NullPointerException is thrown.
Exercise
Name two reasons why a counter that records how many times a job has run is a poor fit for custom metadata.
Show answer
Apex cannot update custom metadata records with DML, so the code cannot increment the counter directly. Changing the value would need an asynchronous Metadata API deployment, which is slow and unsuitable for frequent updates. The value also changes at run time, while custom metadata is meant for configuration that changes by deployment or by an administrator.