How to get a Custom Metadata Record without using a SOQL Query

Author: Bruce Tollefson Published: December 23, 2021; Modified: May 9, 2022
code

Custom Metadata can be used for a variety of reasons one of which is allowing the ability to create a framework from deployable records (custom metadata) instead of data. They can be referenced in formulas, flows, and APEX. If you are not familiar take a look at the Custom Metadata Type Basics and Programmable Development with Custom Metadata Types trailheads.

I will be using a custom metadata named API_Endpoint_Attribute for the demonstration. One way to retrieve a metadata record is to use a query as such:

API_Endpoint_Attribute__mdt folderEndpoint = [Select Id, Label, URL_Path__c from API_Endpoint_Attribute__mdt where DeveloperName = 'Folders'];

A custom metadata query does not use a SOQL query limit however does use the query rows limit. Using a query is good if you need to call a list of custom metadata that could change based on the query or you have large fields with character lengths greater than 255. However if your records don’t have large character lengths or the purpose for getting those records is not to use any of the fields with large lengths the records can be called without creating a query or using query row limits. The getInstance() or the getAll() methods get a singular record(with the Id, developerName, or qualifiedApiName) or all of the records with a Map<String, CustomMetadata__mdt> with the key being the DeveloperName. Here is an example of each:

API_Endpoint_Attribute__mdt folderEndpoint = API_Endpoint_Attribute__mdt.getInstance('Folders'); //single record Map<String, API_Endpoint_Attribute__mdt> folderEndpointList = API_Endpoint_Attribute__mdt.getAll(); //map of all records

The documentation states the getAll() method key is the recordId however when running the following in Anonymous Window the key is the developerName:

Map<String, API_Endpoint_Attribute__mdt> folderEndpointList = API_Endpoint_Attribute__mdt.getAll(); system.debug(folderEndpointList.keySet());

Leave a Reply

Your email address will not be published. Required fields are marked *