+ Start a Discussion
Chetan KapaniaChetan Kapania 

Use Apex Metadata API to add a custom metadata type to an org

public class MetadataExample {
    
    public void updateMetadata() {
        Metadata.CustomMetadata customMetaData = new Metadata.CustomMetadata();
        customMetaData.fullName = 'MyNamespace__MyMetadataTypeName.MyMetadataRecordName';
        
        Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
         customField.field = 'customField__c';
        customField.value = 'New value';
        
        customMetadata.values.add(customField);
        Metadata.DeployContainer deployContainer = new Metadata.DeployContainer();
        deployContainer.addMetadata(customMetadata);
        
        Id asyncResultId = Metadata.Operations.enqueueDeployment(deployContainer,null);
    }
}

Courtsey: https://www.youtube.com/watch?v=4U2M75X5M8Q
Khan AnasKhan Anas (Salesforce Developers) 
Hi Chetan,

Please refer to the below links which might help you further with the above requirement.

https://ashwanisoni.wordpress.com/2017/05/02/create-or-update-custom-metadata-type-via-apex-code-salesforce-summer-17/

https://trailhead.salesforce.com/en/content/learn/modules/apex_metadata_api

https://andyinthecloud.com/2017/08/29/introducing-custom-metadata-services/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Chetan KapaniaChetan Kapania
My query has already been resolved, and passed my Trailhead challenge. I have posted it for those who might get stuck somewhere.
Hrushikesh Pradhan 4Hrushikesh Pradhan 4
public class MetadataExample {
    
    public void updateMetadata() {
        Metadata.CustomMetadata customMetaData = new Metadata.CustomMetadata();
        customMetaData.fullName = 'MyNamespace__MyMetadataTypeName.MyMetadataRecordName';
        
        Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
         customField.field = 'customField__c';
         customField.value = 'New value';
        
        customMetaData.values.add(customField);
        Metadata.DeployContainer deployContainer = new Metadata.DeployContainer();
        deployContainer.addMetadata(customMetaData);
        
        Id asyncResultId = Metadata.Operations.enqueueDeployment(deployContainer,null);
    }
}


Corrected few Typo :) customMetaData instead of customMetadata