No comments yet

Access Custom Metadata Type Records Using Static Methods

In the Salesforce Spring21 pre-release orgs there are new methods for Custom Metadata Types that mirror those on Custom Settings. Removes the need to query them via SOQL and drops the contribution to the Query Rows limit. Use the Apex getAll(), getInstance(recordId), getInstance(qualifiedApiName), and getInstance(developerName) methods to retrieve information from custom metadata type records faster. These methods don’t rely on the SOQL engine and return the sObject details directly from the call.

  1. Removes the need to query them via SOQL
  2. Drops the contribution to the Query Rows limit.
  3. Another bonus with this approach is that it will pick up any field changes automatically as you aren’t explicitly requesting specific fields

Let see how we access the Custom Metadata Type records before Sprint 21

// Before Sprint 21
List<Email_Domain__mdt> listEmailDomain = [SELECT Id,MasterLabel,Domain__c from Email_Domain__mdt];
System.debug('--listEmailDomain->'+listEmailDomain);

getAll() to get Custom Metadata Type Records

Now let see how we can get Custom Metadata Type records with getAll() method.

// Sprint 21 : get custom metadata with getAll
Map<String, Email_Domain__mdt> mapEd = Email_Domain__mdt.getAll();
for(String nameEmailDomain : mapEd.keySet()){
    System.debug('----->'+mapEd.get(nameEmailDomain).Domain__c);
}

getInstance() to get Custom Metadata Type Record

What about if you don’t need to get all record and need to access only single record? In that case you can use the getInstance() method.

// Sprint 21 : get custom metadata with getInstance();
Email_Domain__mdt emailDomain = Email_Domain__mdt.getInstance('gmail');
System.debug('----->'+emailDomain);

Post a comment