Sub topic 10
Linking types with metadata relationship fields
This chapter assumes you can define a custom metadata type, create records for it, and query it with SOQL. It covers the metadata relationship field type. It lets one custom metadata record point at another record, at an object, or at a field. By the end you should be able to model parent and child configuration, read related values in Apex, and avoid the deployment and testing problems that come with these links.
Why link configuration records
Configuration often has a shape. Several operations may share one endpoint. Several discount rules may share one tier. If you store the shared value as plain text on every child record, you have copied it. When it changes, you have to edit every copy, and you can miss one.
A metadata relationship field fixes this. The child record stores a reference to a parent record. The parent holds the shared values once. Salesforce also validates the reference, so a typo in a text field cannot silently point at nothing.
A metadata relationship is not a lookup or master-detail relationship. Those link rows in custom objects. A metadata relationship is defined on a custom metadata type. It links metadata, not data. You cannot use it from a custom object to point at a custom metadata record.
What a metadata relationship can point to
When you add a field of type Metadata Relationship in Setup, you choose the kind of target.
| Target | What the field stores | Typical use |
|---|---|---|
| Another custom metadata type | A reference to one record of that type | Shared parent settings, such as an endpoint or a tier |
| Entity Definition | A reference to an object, standard or custom | Config that applies to a specific object, such as `Account` |
| Field Definition | A reference to a field on an object | Config that names a field, such as a field to copy or validate |
The object and field targets are useful because they replace free-text API names. If you type Acount into a text field, nothing complains until runtime. A relationship to an entity definition is selected from a list of real objects, so the name is valid when you save it.
Defining the fields
The running example has two types.
Integration_Endpoint__mdthas a text fieldBase_URL__cand a number fieldTimeout_Seconds__c. Each record is one external system, such asBilling_Api.Integration_Operation__mdthas a text fieldPath__cand a metadata relationship fieldEndpoint__cthat points toIntegration_Endpoint__mdt. Each record is one call, such asGet_Invoice.
To create the relationship field:
- In Setup, open Custom Metadata Types and select
Integration_Operation. - In Custom Fields, click New.
- Choose Metadata Relationship as the data type.
- Under Related To, choose Custom Metadata Type, then pick
Integration_Endpoint. - Enter the label
Endpointand save. The API name becomesEndpoint__c, and the relationship name used in SOQL isEndpoint__r.
You can mark the field as required, so a record cannot be saved without a parent.
Setting the reference in a record
In the Setup UI, the child record page shows a lookup-style picker for the relationship field. In source format, the reference is stored by name. The value is the developer name of the parent record. For an entity definition it is the object API name, such as Account.
This is the file Integration_Operation.Get_Invoice.md-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<label>Get Invoice</label>
<protected>false</protected>
<values>
<field>Endpoint__c</field>
<value xsi:type="xsd:string">Billing_Api</value>
</values>
<values>
<field>Path__c</field>
<value xsi:type="xsd:string">/invoices/{id}</value>
</values>
</CustomMetadata>The reference is by developer name, not by an Id. That is what makes the records portable. The same file works in a sandbox and in production as long as a Billing_Api record exists in both.
Reading related values in Apex
Related values are read with SOQL. Traverse the relationship with __r and name the parent's fields.
public with sharing class OperationUrlBuilder {
public class ConfigException extends Exception {}
public static String buildUrl(String operationName) {
List<Integration_Operation__mdt> operations = [
SELECT DeveloperName, Path__c,
Endpoint__r.DeveloperName,
Endpoint__r.Base_URL__c
FROM Integration_Operation__mdt
WHERE DeveloperName = :operationName
LIMIT 1
];
if (operations.isEmpty()) {
throw new ConfigException('No operation named ' + operationName);
}
Integration_Operation__mdt operation = operations[0];
if (operation.Endpoint__r == null) {
throw new ConfigException(operationName + ' has no endpoint');
}
return operation.Endpoint__r.Base_URL__c + operation.Path__c;
}
}Three details matter here.
- Select the parent fields you need through
Endpoint__r. A parent field you did not select is not available on the result. - Do not rely on the raw value of
Endpoint__citself. UseEndpoint__r.DeveloperNamewhen you need to identify the parent. - Check
Endpoint__rfor null. If the field is not required, a child can legitimately have no parent.
Why not getInstance() and getAll()
getInstance() and getAll() are cheaper than SOQL because they do not count against query limits. They return the record's own fields. They do not follow relationship fields, so Endpoint__r.Base_URL__c is not available on a record from getInstance().
You can still avoid SOQL if you accept two lookups. Read the child with getInstance(), take the parent's developer name from your own convention (for example, a text field), and call getInstance() on the parent type. This costs a second lookup and gives up the validation that the relationship field provides. In most cases, use one SOQL query with a __r traversal.
Linking to objects
A relationship to an entity definition returns the object's API name when you select Object__r.QualifiedApiName. You can use that string with the schema describe methods.
List<Sync_Config__mdt> configs = [
SELECT DeveloperName, Object__r.QualifiedApiName
FROM Sync_Config__mdt
];
Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();
for (Sync_Config__mdt config : configs) {
String objectName = config.Object__r.QualifiedApiName;
Schema.SObjectType sobjectType = globalDescribe.get(objectName);
System.debug(config.DeveloperName + ' applies to ' + sobjectType.getDescribe().getLabel());
}This is the safe alternative to a text field holding 'Account'. The reference is validated when the record is saved, and you read it as a normal string at runtime.
Deployment order and dependencies
A relationship is a dependency. The child record cannot exist without its target.
- Deploy the parent type, the parent records, the child type, and the child records together when you can. A single deployment resolves the order for you.
- If you split deployments, the parent type and its records must arrive first. A child record that names a missing parent fails validation.
- Expect resistance when you try to delete a parent that other records reference. Update or delete the children first.
- If the target is an object or field, that object or field must exist in the destination org. A field that exists only in a sandbox blocks the deployment.
Keep parent records free of environment-specific values when you plan to promote them. A Base_URL__c that differs per org is better handled with a named credential, with the record holding only the credential name.
Testing code that uses relationships
You cannot insert custom metadata records with DML in a test, so you cannot build a parent and child pair in test setup. Two approaches work.
- Test against deployed records. The test queries real records. This couples the test to the org's configuration and breaks when a record is renamed.
- Put the lookup behind a small method and override it. The class that reads configuration returns plain Apex values, and the test replaces it with a stub.
The second approach follows the same @TestVisible pattern shown for feature flags earlier in this tutorial. A common version is a private static variable that holds a list of already-built records. For relationship values, you can build a record in memory with JSON.deserialize on a map that includes the nested Endpoint__r object, and then return it from the override. This keeps the test independent of the org.
Common errors
- Null
__rat runtime. The relationship field is optional, or the parent was not selected in the query. Select the parent fields explicitly and check for null. - Using
getInstance()and expecting parent data. Relationship traversal is only available in SOQL. - Deployment fails with a missing reference. The parent record, or the referenced object or field, is not in the target org. Include it or deploy it first.
- Renaming a parent's developer name. Child references are by name. Rename in source and update all children in the same deployment.
- Choosing a relationship where plain text is enough. A single value used by one record gains nothing from a parent type. Use a relationship when two or more records share data.
Exercise
A class reads IntegrationOperationmdt with getInstance('GetInvoice') and then tries to read operation.Endpoint_r.BaseURL__c. What goes wrong, and how do you fix it?
Show answer
getInstance() returns only the record's own fields and does not follow metadata relationship fields, so Endpoint_r is not populated and the read fails or returns null. Fix it by querying with SOQL and selecting the parent fields, for example SELECT Pathc, Endpointr.BaseURL_c FROM IntegrationOperation_mdt WHERE DeveloperName = 'GetInvoice', then checking Endpoint__r for null.
Exercise
You need configuration that says which object a handler applies to. Why use a metadata relationship to an entity definition instead of a text field holding the object name?
Show answer
The relationship is validated when the record is saved, so a misspelled or nonexistent object cannot be stored, and the deployment checks that the object exists in the target org. A text field accepts any string and fails only at runtime.