Skip to content
SFDC Madhukar

SFDC Madhukar

  • Home
  • Blogs
  • Gallery
  • TrainingExpand
    • Admin Training
    • Apex Training
    • LWC Training
    • Integration Training
    • Flow Training
  • About Us
  • Contact Us
SFDC Madhukar
SFDC Madhukar
How to Create/Update Custom Metadata with Apex
  • All, Apex, Other Blogs

How to Create/Update Custom Metadata with Apex

  • By Ashish Madhukar
  • September 8, 2024

Introduction: To create a new record in a custom metadata type using Apex in Salesforce, you must first load the Metadata namespace, which contains the classes and methods required to manage metadata records. Custom metadata records, unlike ordinary objects, are metadata themselves, and hence cannot be generated or edited using standard DML operations (such as insert, update). Instead, you must use the Metadata.Operations class to generate and publish metadata.

Step-by-Step Guide to Create a New Record in Custom Metadata

Enable Apex Metadata API : Ensure that the Apex Metadata API is enabled in your Salesforce organization. This is normally available in the Developer and Enterprise editions.

To activate the Apex Metadata API, pick either the Deploy Change Sets or Author Apex permissions. This will immediately enable the Modify Metadata using Metadata API Functions access, allowing you to deploy Apex metadata.

System Administrator have these are permission if you want to non-System Administrator user then you an give using permission set.

Permission Set : Create permission set and enable below permission.

Go to setup=> Permission set=> create new permission set.

After that click on Save

Then you can give access on permission set.

Checked above checkbox and assign Author Apex permission to non- System Administrator.

Create Custom Metadata: create custom metadata in your org. for example i am taking Currency Master

Go to Setup => Custom metadata => New

  1. Create Custom fields in custom metadata, it should be text type, see above screenshot.

Create Apex Class to Insert Custom Metadata Record: Use the Apex code snippet below to create a new record in a custom metadata type.

Create Operation: Custom Metadata create operation.

Copy CodeCopiedUse a different Browser
// Apex class to create a new record in custom metadata type
public class CustomMetadataCreator {
    public static void createCurrencyMasterRecord() {
        // Create a custom metadata record
        Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
        
        // Set the fullName using the custom metadata type's object name and the developer name of the record
        customMetadata.fullName = 'Currency_Master__mdt.USD'; //Use the Apex code snippet below to create a new record in a custom metadata type.
        customMetadata.Label = 'Currency_Master__mdt.USD'; // 'USD' is the developer name of the record
      

        // Create a field for the 'Currency_Code__c' custom field in Currency_Master__mdt
        Metadata.CustomMetadataValue currencyCodeField = new Metadata.CustomMetadataValue();
        currencyCodeField.field = 'Currency_Code__c';
        currencyCodeField.value = 'USD';  // Setting the Currency Code to 'USD'

        // Create a field for the 'Currency_Label__c' custom field in Currency_Master__mdt
        Metadata.CustomMetadataValue currencyLabelField = new Metadata.CustomMetadataValue();
        currencyLabelField.field = 'Currency_Label__c';
        currencyLabelField.value = 'US Dollar';  // Setting the Currency Label to 'US Dollar'

        // Add the custom metadata values to the metadata record
        customMetadata.values.add(currencyCodeField);
        customMetadata.values.add(currencyLabelField);

        // Create an instance of the Metadata API deploy request
        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(customMetadata);

        // Deploy the metadata changes
        Metadata.DeployCallback callback = new CustomMetadataDeployCallback();
        Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
        System.debug('Deployment Job ID: ' + jobId);
    }

// Callback class to handle the deployment results
public class CustomMetadataDeployCallback implements Metadata.DeployCallback {
    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            System.debug('Custom Metadata Record creation succeeded.');
        } else {
            System.debug('Custom Metadata Record creation failed. Errors: ' + result);
        }
    }
}
}

Result : See below screenshot

Explanation of the Apex Code:

  1. Metadata.CustomMetadata: Generates an instance of the custom metadata record.
  2. customMetadata.fullName: Defines the full name of the custom metadata record, which is a mix of the metadata type name (Currency_Master__mdt) and the record’s developer name (USD in this example).
  3. customMetadata.Label: Define the Label is Master Label which required field to create custom metadata.
  4. Metadata.CustomMetadataValue: Creates instances of each field (Currency_Code__c and Currency_Label__c) that you want to set on the custom metadata record.
  5. Metadata.DeployContainer: Stores all metadata updates to be deployed.
  6. Metadata.Operations.enqueueDeployment: Asynchronously deploys the metadata, with the outcome handled via a callback (CustomMetadataDeployCallback).

Apex Code for Update Operations:

Copy CodeCopiedUse a different Browser
// Apex class to create a new record in custom metadata type
public class CustomMetadataCreator {
    
    // Method to update an existing custom metadata record
    public static void updateCurrencyMasterRecord() {
        Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();
        customMetadata.fullName = 'Currency_Master__mdt.USD'; // Identify the record to update
		customMetadata.Label = 'Currency_Master__mdt.USD';
        Metadata.CustomMetadataValue currencyLabelField = new Metadata.CustomMetadataValue();
        currencyLabelField.field = 'Currency_Label__c';
        currencyLabelField.value = 'US Dollar Updated'; // New value to be updated

        customMetadata.values.add(currencyLabelField);

        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(customMetadata);

        Metadata.DeployCallback callback = new CustomMetadataDeployCallback();
        Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
        System.debug('Update Operation - Deployment Job ID: ' + jobId);
    }


// Callback class to handle the deployment results
public class CustomMetadataDeployCallback implements Metadata.DeployCallback {
    public void handleResult(Metadata.DeployResult result, Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            System.debug('Custom Metadata Record creation succeeded.');
        } else {
            System.debug('Custom Metadata Record creation failed. Errors: ' + result);
        }
    }
}
}

Result :

SUBSCRIBE OUR YOUTUBE CHANNEL

We provide all types of salesforce videos on this channel. Admin, Developer, Architect, and New Release Facts, Subscribe to our channel to stay up to date on everything Salesforce.

SUBSCRIBE

Similar Posts

Client Side Pagination in LWC using JavaScript

Client Side Pagination in LWC using JavaScript

July 21, 2024 No Comments
Enabling Developer Console Using Permission Sets for Non-Admin Users

Enabling Developer Console Using Permission Sets for Non-Admin Users

July 19, 2024 No Comments

How to Control Apex Trigger in Production Using Custom Settings

July 16, 2024 No Comments

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Contact us

sfdcdevmadhukar@gmail.com

Quick Links

Blogs

Gallery

About Us

Contact Us

Privacy Policy

Terms & Conditions

Follow Us On

X YouTube Linkedin WhatsApp

© 2025 SFDC Madhukar

Scroll to top
  • Home
  • Blogs
  • Gallery
  • Training
    • Admin Training
    • Apex Training
    • LWC Training
    • Integration Training
    • Flow Training
  • About Us
  • Contact Us