Salesforce Summer 17 came with a most wanted feature for Custom Metadata Types which is managing it via Apex code. Now custom metadata records can be create and updated via Apex code which means no changes set or force.com migration tool is required from Summer 17.
There is a Namespace called Metadata introduced in Summer ’17 release to manage Custom Metadata.
Below is the sample code to create a Custom metadata type:-
First define a Metadata in org the same as previous releases. Here Response_Type__mdt is created.
Add new field Status_Code__c.
Here our purpose is to configure status codes by Custom Metadata proper message can be displayed.
New Metadata would look like as below:-

Few things to consider:-
- Custom Metadata create/update is asynchronous
- It actually does a deployment in backend instead of DML
- Doesn’t count against governor limit
Because the Custom Metadata update happens asynchronous it requires a way to get the status of deployment. So, it requires callback class. Lets define a callback class as:-
public class CustomMetadataCallback implements Metadata.DeployCallback {
public void handleResult(Metadata.DeployResult result,
Metadata.DeployCallbackContext context) {
if (result.status == Metadata.DeployStatus.Succeeded) {
System.debug('success: '+ result);
} else {
// Deployment was not successful
System.debug('fail: '+ result);
}
}
}
A callback class implement Metadata.DeployCallback interface.
Below is the way to create a custom Metadata:-
// Set up custom metadata to be created in the subscriber org.
Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
customMetadata.fullName = 'Response_Type.Not_Found_Code';
customMetadata.label = 'Not_Found_Code';
Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
customField.field = 'Status_Code__c';
customField.value = '404';
customMetadata.values.add(customField);
Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
mdContainer.addMetadata(customMetadata);
// Setup deploy callback, MyDeployCallback implements
// the Metadata.DeployCallback interface (code for
// this class not shown in this example)
CustomMetadataCallback callback = new CustomMetadataCallback();
// Enqueue custom metadata deployment
// jobId is the deployment ID
Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
By executing the above code we can create a Custom Metadata record in Response_Type__mdt custom Metadata.
All failures and success can be traced in callback class CustomMetadataCallback‘s method handleResult.
In addition deployment result can be checked in Setup -> Deploy | Deployment Status as shown below:
This is how we an create Custom Metadata record. It has been the most demanded feature since Custom Metadata introduced. Hope that will help a lot in Custom Metadata based implementations.
Useful links:-