Biswajeet Samal's Blog

Sharing My IT Experience

  • Home

Create Or Update Custom Metadata Type Using Apex

Biswajeet   November 6, 2018   No Comments on Create Or Update Custom Metadata Type Using Apex
  • We cannot Create or Update Custom Metadata records using DML statement.
  • We can Create or Update Custom Metadata records using apex Metadata deployment.
  • To do the Metadata deployment using apex, it requires a callback class with Metadata.DeployCallback interface.

Sample Metadata Deployment Callback Class:

public class CustomMetadataCallBack implements Metadata.DeployCallback {
    
    //Inteface method 
    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            //Success
        } else {
            //Failed
        }
    }
}

Here I have created a Custom Metadata Type (Tax Setting), to save Tax related information for an Application.

Here I have created a class with Metadata.DeployCallback interface, and two methods to create and update Custom Metadata Type records.

Apex Class:

public class CustomMetadataUtils implements Metadata.DeployCallback {
    
    //Inteface method 
    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            //Success
            System.debug('Success Result-' + result);
        } else {
            //Failed
            System.debug('Failed Result-' + result);
        }
    }
    
    //Create Custom Metadata record
    public static void createCustomMetadata(String metdataName, String label, Map<String, Object> metadataFieldValueMap){
        String recordDevName = label.replaceAll(' ', '_');
        Metadata.CustomMetadata cMetadata = new Metadata.CustomMetadata();
        cMetadata.fullName = metdataName + '.' + recordDevName;
        cMetadata.label = label;
        
        for(String key : metadataFieldValueMap.keySet()){
            Metadata.CustomMetadataValue cMetadataValue = new Metadata.CustomMetadataValue();
            cMetadataValue.Field = key;
            cMetadataValue.Value = metadataFieldValueMap.get(key); 
            cMetadata.values.add(cMetadataValue);
        }
        
        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(cMetadata);
        CustomMetadataUtils callback = new CustomMetadataUtils();
        Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
    }
    
    //Update Custom Metadata record
    public static void updateCustomMetadata(String metdataName, String recordDevName, String label, Map<String, Object> metadataFieldValueMap){
        Metadata.CustomMetadata cMetadata = new Metadata.CustomMetadata();
        cMetadata.fullName = metdataName + '.' + recordDevName;
        cMetadata.label = label;
        
        for(String key : metadataFieldValueMap.keySet()){
            Metadata.CustomMetadataValue cMetadataValue = new Metadata.CustomMetadataValue();
            cMetadataValue.Field = key;
            cMetadataValue.Value = metadataFieldValueMap.get(key); 
            cMetadata.values.add(cMetadataValue);
        }
        
        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(cMetadata);
        CustomMetadataUtils callback = new CustomMetadataUtils();
        Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
    }
}

To test above class methods, you can run below code in developer console.
Create Custom Metadata Record:

Map<String, Object> metadataFieldValueMap = new Map<String, Object>();
metadataFieldValueMap.put('TaxPercent__c', 4);
CustomMetadataUtils.createCustomMetadata('SalesTaxSetting__mdt', 'Value Added Tax', metadataFieldValueMap);

Update Custom Metadata Record:

Map<String, Object> metadataFieldValueMap = new Map<String, Object>();
metadataFieldValueMap.put('TaxPercent__c', 15);
CustomMetadataUtils.updateCustomMetadata('SalesTaxSetting__mdt','Value_Added_Tax', 'Value Added Tax',metadataFieldValueMap);

After deployed the Custom Metadata, you can check the deployment status.
Go to Setup | Deploy | Deployment Status | Check the deployment status

Salesforce     Apex, Custom Metadata Type
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Related posts

  • »  Salesforce Apex Trigger Framework
  • »  Get Salesforce Org Limits Using Apex
  • »  Salesforce Apex TriggerOperation Enum
  • »  Get Salesforce Logged In Users Using Apex
  • »  Salesforce User Logout Event Trigger

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

View all posts by Biswajeet →

Post navigation

← Inherited Sharing in Apex Class Invoke Flow From Lightning Component With Input Variables →

Get In Touch

Facebook   Twitter  LinkedIn  RSS Feed  Email

Trailblazer Community Profile

Trailblazer Community Profile

Technologies

  • .Net (7)
  • Computer Tips & Tricks (2)
  • Eclipse (2)
  • HTML (6)
  • JavaScript (26)
  • MS SQL Server (9)
  • PHP (1)
  • Salesforce (666)
  • ‎jQuery (1)

Tags

.Net Apex Apex Class Apex Trigger API Approval Process Batch Apex Batch Class C# Force.com Formula Field Javascript Json Lightning lightning:recordeditform Lightning Component Lightning Data Service Lightning Framework Lightning Out Lightning Web Component List LWC Modal MS SQL Server Object Picklist Process Builder Profile Quick Action Record Type REST API Salesforce Salesforce.com Salesforce Tips & Tricks SFDC sObject SOQL SOSL SQL Server Tips & Tricks StandardController Test Class Trigger User Validation Rule Visualforce Page

Salesforce Blogs Member

Salesforce Blogs Member

10 Most Popular Salesforce Developer Blogs

Salesforce Top 50 Developer Blog Winner

Top 50 Salesforce Developer Blogs

Salesforce Top 50 Developer Blog Winner

Visitors

Biswajeet Samal

Biswajeet Samal

Recent Tweets

Tweets by @itzbiswajeet
Copyright © 2018 || Biswajeet Samal's Blog
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject