Sub topic 3
Defining a type and its fields
A custom metadata type is the schema for your configuration. You define it once, then create records against it. This chapter covers how to create the type, which settings matter, which field types you can use, and how the fields appear in Apex.
This chapter assumes you can navigate Salesforce Setup, know how custom objects and fields work, and can read basic Apex and SOQL. Records are covered in the next chapter, so here you only build the structure.
What you are creating
A type is like a custom object with a __mdt suffix. Its fields use the usual __c suffix. Each record of the type is metadata, not data. It deploys with your code and is readable from Apex without consuming SOQL query limits when you use the getInstance() and getAll() methods.
Creating the type in Setup
In Setup, search for Custom Metadata Types and click New Custom Metadata Type. The form asks for these values:
| Setting | What it does |
|---|---|
| Label | The name shown in Setup and the UI. |
| Plural Label | The name used when the UI lists several records. |
| Object Name | The API name. Setup adds `__mdt` automatically. |
| Visibility | Controls who can see the type when it is in a managed package. |
| Description | Free text for other admins and developers. |
Treat the Object Name as permanent. Apex code, SOQL, and deployment files all refer to it, so renaming later means touching every reference. Use a singular noun in Pascal_Snake_Case, such as Feature_Flag or Discount_Rule. Plural labels belong in the label, not the API name.
Visibility has three options in the UI. Public lets any code and any admin in the org read and use the type. When you build a managed package, the two package-related options restrict visibility to the package or let subscribers see only some of the data. Visibility is covered in detail later, and for an org-only project Public is the normal choice.
You can also create the type in a source-format project. This is the file force-app/main/default/objects/Feature_Flag__mdt/Feature_Flag__mdt.object-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Feature Flag</label>
<pluralLabel>Feature Flags</pluralLabel>
<visibility>Public</visibility>
<description>Turns application features on or off without a code change.</description>
</CustomObject>The folder name must match the API name, including __mdt.
Fields every record already has
You get several fields without defining anything. Apex and SOQL can read them on any type.
| Field | Meaning |
|---|---|
| `DeveloperName` | The unique API name of the record within its type. Used with `getInstance()`. |
| `MasterLabel` | The record's label, in the org's default language. |
| `Label` | The label translated for the running user's language. |
| `QualifiedApiName` | The developer name, with the namespace prefix when there is one. |
| `NamespacePrefix` | The namespace of the package that owns the record, or null. |
| `Language` | The language of the label. |
DeveloperName is the most important of these. It acts as the primary key for lookups, so you rarely need to add an "ID" or "Code" field of your own. A region record can use US as its developer name and be looked up directly with Tax_Strategy__mdt.getInstance('US').
Choosing field types
Custom metadata types support a smaller set of field types than custom objects. The common ones, with the Apex type each maps to, are:
| Setup field type | Apex type | Typical use |
|---|---|---|
| Checkbox | `Boolean` | Flags such as `Is_Enabled__c` |
| Number | `Decimal` | Thresholds, limits, amounts |
| Percent | `Decimal` | Discount rates, tolerances |
| Text | `String` | Codes, class names, endpoints |
| Text Area | `String` | Longer descriptions or messages |
| Picklist | `String` | A fixed set of modes or levels |
| Date and Date/Time | `Date`, `Datetime` | Effective dates, cut-off times |
| Email, Phone, URL | `String` | Contact details, endpoints |
| Metadata Relationship | `String` (plus a `__r` reference) | Pointing at an object, field, or another type |
Note what is missing. There are no lookup or master-detail relationships to ordinary objects, and no automatic-number fields. The Metadata Relationship type is a separate topic, covered in its own chapter.
The Percent type stores the number as written. A value of 15 means 15 percent, so divide by 100 yourself when you calculate a discount.
Field settings that matter
When you create a field, the settings below affect how safe your configuration is.
- Required. A required field blocks saving a record that leaves it empty. Use it for values your code depends on, so a missing value fails when an admin saves the record and not when a user triggers the code.
- Default value. Checkbox fields always need one. Setting
falsefor a feature flag makes new flags start disabled. - Field manageability. In a package, this decides whether subscribers can change the value. Without packaging it has little effect, but it is part of the field definition.
- Help text. Admins edit these records by hand, so a sentence explaining units or allowed values prevents mistakes.
- Length and precision. A Text field has a maximum length and a Number field has precision and scale. Pick values that match what the code expects. Setting
Min_Amount__cto 18 digits and 2 decimals is enough for currency thresholds.
Here is the matching source file for the checkbox field, fields/Is_Enabled__c.field-meta.xml inside the Feature_Flag__mdt folder:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Is_Enabled__c</fullName>
<label>Is Enabled</label>
<defaultValue>false</defaultValue>
<fieldManageability>DeveloperControlled</fieldManageability>
<inlineHelpText>Check to turn the feature on for all users.</inlineHelpText>
<type>Checkbox</type>
</CustomField>And a number field for a Discount_Rule__mdt type:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Min_Amount__c</fullName>
<label>Minimum Amount</label>
<required>true</required>
<precision>18</precision>
<scale>2</scale>
<fieldManageability>DeveloperControlled</fieldManageability>
<inlineHelpText>Orders at or above this total qualify for this tier.</inlineHelpText>
<type>Number</type>
<unique>false</unique>
</CustomField>Using the fields in Apex
Once the type and fields exist, Apex sees them as strongly typed members of the generated Feature_Flag__mdt class. That means a typo in a field name fails at compile time, which is one advantage over reading free-form text from a map or label.
Discount_Rule__mdt rule = Discount_Rule__mdt.getInstance('Gold');
if (rule != null) {
String label = rule.MasterLabel;
String devName = rule.DeveloperName;
Decimal minAmount = rule.Min_Amount__c;
Decimal percent = rule.Percent__c;
System.debug(devName + ': ' + percent + '% from ' + minAmount);
}The fields are read-only. Assigning rule.Percent__c = 20; compiles, but the change exists only in that in-memory copy, and nothing is saved. Changing a stored value needs the Metadata API, covered in a later chapter.
Design guidelines for fields
- One concept per type. Keep feature flags in one type, discount tiers in another. A type with many unrelated optional fields becomes hard to explain and validate.
- Name fields for what code uses.
Class_Name__candIs_Active__care clearer thanValue1__c. - Prefer typed fields over encoded text. Use a Checkbox for a boolean and a Number for a threshold. Avoid storing
trueor250in a Text field and parsing it. - Add an active flag when records may need retiring. A checkbox such as
Is_Active__clets admins disable a record without deleting it, which is safer in a deployed org. - Think about the future before packaging. Once a field is released in a managed package, you cannot delete it or change its type. Use the field settings above carefully.
Exercise
You need configuration for retry behavior: a maximum number of attempts, a delay in seconds, and whether retries are turned on. Which custom metadata type fields would you create, and why is DeveloperName a good place to put the name of the integration being configured?
Show answer
Create a Number field such as Max_Attempts__c with scale 0, a Number field such as Delay_Seconds__c, and a Checkbox such as Is_Enabled__c with a default of false. Mark the numeric fields required so an incomplete record cannot be saved. Each record's DeveloperName can hold the integration name, for example Payment_Gateway. It is unique within the type, so getInstance('Payment_Gateway') finds exactly one record and no separate ID field is needed.