Sunday, April 3, 2022

How to Update custom metadata type record using Metadata API

 In this example, I'll show you how can we write an Apex class to update the custom metadata record using Metadata API

Please follow the below steps:

Step 1 : Create a Custom metadata object and a field, in our example our custom metadata object is StatesCitiesPincode__mdt and a custom field State__c

Step 2: Create a record by clicking on the Manage StatesCitiesPincode button at the top and then click on the new button

Step 3: Now we'll create an apex class which will be used to update the record, whenever we update the custom metadata record using metadata API the system does an actual deployment and we can track it by checking deployment Status through the Setup.


  public class CreateUpdateMetadataUtils implements Metadata.DeployCallback {
    // Method to track deploy results
    public void handleResult(Metadata.DeployResult result,
                             Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            System.debug('success: '+ result);
        } else {
            System.debug('fail: '+ result);
        }
    }
}
  

  public with sharing class UpdateCustomMetadata {
    
    public static void updateRecord() {
        
        try {                
            Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
            
            Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
            customMetadata.fullName = 'StatesCitiesPincode__mdt.Uttar_Pradesh';
            customMetadata.Label='Uttar Pradesh';
            
            Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
            customField.field = 'State__c';
            customField.value = 'UP';
            
            
            customMetadata.values.add(customField);                
            mdContainer.addMetadata(customMetadata);            
            
              
            CreateUpdateMetadataUtils  callback = new CreateUpdateMetadataUtils();            
            Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);                        
            
            
        } catch (exception e) {
            
        }                
    }        
}
  

you can execute the method from the Anonymous Apex window UpdateCustomMetadata.updateRecord();

No comments:

Post a Comment