Saturday, 22 June 2019

Custom Metadata Record creation in apex

Hi,

Here I am going to explain how can we create custom metadata record in apex.

Usually, we can' create custom metadata record through DML statements in apex.


But we have  "Metadata" class to create Custom Metadata record in apex.

When we use this no DML operations happen for creating records. instead, it does the deployment of custom metadata values.

Whenever we want to use this we have to create a call back class which implements "Metadata.DeployCallback" interface as shown below as this action is asynchronous.

Callback Class:
public class MetadataCallbackCls implements Metadata.DeployCallback {
    public void handleResult(Metadata.DeployResult result,
                             Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            System.debug('success: '+ result);
        } else {         
            System.debug('fail: '+ result);
        }
    }
}


Example Snippet for creating Custom Meta Data:


Let's take custom metadata type "User_Creds__mdt" which has a custom field "Password__c".

To insert a record into the same we have to follow the same below.

    Metadata.CustomMetadata customMetadataObj =  new Metadata.CustomMetadata();
    customMetadataObj .fullName = 'User_Creds__mdt.Balaji_M';
    customMetadataObj .label = 'Balaji_M';

    Metadata.CustomMetadataValue customFieldObj = new Metadata.CustomMetadataValue();
    customFieldObj .field = 'Password__c';
    customFieldObj .value = 'XXXXX';

    customMetadataObj.values.add(customFieldObj);

    Metadata.DeployContainer containerObj= new Metadata.DeployContainer();
    containerObj.addMetadata(customMetadataObj);


    MetadataCallbackCls  callback = new MetadataCallbackCls ();
 
    Id jobId = Metadata.Operations.enqueueDeployment(containerObj, callback);


Output:




References:

https://developer.salesforce.com/docs/atlas.en-us.208.0.apexcode.meta/apexcode/apex_class_Metadata_CustomMetadata.htm#apex_class_Metadata_CustomMetadata


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

https://trailhead.salesforce.com/en/content/learn/modules/custom_metadata_types_adv/cmt_develop

https://developer.salesforce.com/docs/atlas.en-us.208.0.apexcode.meta/apexcode/apex_interface_Metadata_DeployCallback.htm#apex_Metadata_DeployCallback_methods

1 comment:

  1. Spending days in creating fields or objects? now create upto 500 fields in few clicks. Want to know how? simply follow the given link - Mass “Create Custom Fields” for multiple objects in single click in Salesforce

    ReplyDelete

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...