DML On Custom Metadata Salesforce

You can see exact output for this implementation to the below video. Please let me know if you want more clarification over this implementation connect me on whatsapp: 8055257676

DML On Custom Metadata Dynamically using Lightning and Aura Enabled Apex Method

In this Blog I have explained #How to fetch Object API name by Dynamic Apex, #How to fetch Field Label of Object by Dynamic Apex, #How to fetch Fieldname by object name by dynamic apex, #How to fetch Relationship name of object by dynamic apex, #How to insert/update data into Custom Metadata dynamically, #How to fetch data from Custom Metadata and show on UI.

Below screen you can see that I have created one lightning component. This Component is divided into two column. #1 Column – Entity – Relationship – Filed and #2 Column

Step 1: Created Below Custom Metadata

Step 2 : Created Lightning Component – JsonCreatorCmp.cmp and copy paste below code

<aura:component controller="JsonCreatorController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    <aura:attribute name="finalJsonString" type="String" default=""/>   
    
    
    <aura:attribute name="ObjectNames" type="list" />    
    <aura:attribute name="FieldNames_1" type="list" /> 
    <aura:attribute name="FieldNames_2" type="list" /> 
    
    
    
    <aura:attribute name="RelationNames_1" type="list" /> 
    <aura:attribute name="RelationNames_2" type="list" /> 
    
    
    <aura:attribute name="jsonLabel" type="string"  />
    
    <aura:attribute name="loaded" type="Boolean" default="true" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <div class="exampleHolder">
        <aura:if isTrue="{! v.loaded }">
            <div class="backgroundInverse">
                <lightning:spinner alternativeText="Loading" />
            </div>        
        </aura:if>
    </div>
    
    <div style="background:white;min-height:600px;padding:20px;border:1px solid #000;">
        <div class="slds-grid slds-wrap">
            <div class="slds-col slds-size_1-of-1 slds-small-size_1-of-2 slds-medium-size_1-of-2" style="border:1px solid #cacaca;">
                <!--Section 1-->
                
                <div class="slds-grid" aura:id="Sec_1_1">
                    <div class="slds-col slds-size_1-of-1">
                        <div class="slds-grid" aura:id="objectSec_1_1">
                            <div class="slds-col slds-size_11-of-12" style="padding:10px;" >
                                <lightning:select aura:id="ObjPicklistSec_1_1"  name="{!v.name}" label="Entity"  onchange="{!c.PopulateFieldsName}">
                                    <aura:iteration items="{!v.ObjectNames}" var="ob">
                                        <option value="{!ob}">{!ob}</option>
                                    </aura:iteration>
                                    
                                </lightning:select>
                            </div>
                            <div class="slds-col slds-size_1-of-12" style="padding-top:30px;"  >
                                
                                <lightning:buttonIcon aura:id="btnAddObjectSec_1_1" 
                                                      name= "btnAdd"
                                                      iconName="utility:add"
                                                      class="btnIcon"
                                                      variant="brand"
                                                      onclick="{!c.ShowNextObject}"
                                                      />
                                
                            </div>
                        </div>
                        <div class="slds-grid" aura:id="relationSec_1_1">
                            <div class="slds-col slds-size_1-of-12" style="padding:10px;" >                                
                            </div>
                            <div class="slds-col slds-size_10-of-12" style="padding:10px;" >
                                <lightning:select aura:id="relationPicklistSec_1_1"  onchange="{!c.PopulateFieldLabel}" label="Relationship">
                                    <aura:iteration items="{!v.RelationNames_1}" var="rd">
                                        <option value="{!rd}">{!rd}</option>
                                    </aura:iteration>
                                </lightning:select> 
                            </div>
                            <div class="slds-col slds-size_1-of-12" style="padding-top:30px;"  >
                            </div>
                        </div>
                        <div class="slds-grid" aura:id="fieldSec_1_1">
                            <div class="slds-col slds-size_1-of-12" style="padding:10px;" >
                                
                            </div>
                            <div class="slds-col slds-size_10-of-12" style="padding:10px;" >
                                <lightning:select aura:id="fieldPicklistSec_1_1"  onchange="{!c.PopulateFieldLabel}" label="Field">
                                    <aura:iteration items="{!v.FieldNames_1}" var="fd">
                                        <option value="{!fd}">{!fd}</option>
                                    </aura:iteration>
                                </lightning:select> 
                            </div>
                            <div class="slds-col slds-size_1-of-12" style="padding-top:30px;"  >
                                
                                <lightning:buttonIcon aura:id="btnAddfieldSec_1_1" 
                                                      name= "btnAdd"
                                                      iconName="utility:add"
                                                      class="btnIcon"
                                                      variant="brand"
                                                      onclick="{!c.ShowNextField}"
                                                      />
                            </div>
                        </div>
                        <div class="slds-grid hideFields" aura:id="fieldSec_1_2">
                            <div class="slds-col slds-size_1-of-12" style="padding:10px;" ></div>
                            <div class="slds-col slds-size_9-of-12" style="padding:10px;" >
                                <lightning:select aura:id="fieldPicklistSec_1_2"  onchange="{!c.PopulateFieldLabel}" label="Field">
                                    <aura:iteration items="{!v.FieldNames_1}" var="fd">
                                        <option value="{!fd}">{!fd}</option>
                                    </aura:iteration>
                                </lightning:select> 
                            </div>
                            <div class="slds-col slds-size_2-of-12" style="padding-top:30px;"  >
                                
                                <lightning:buttonIcon aura:id="btnAddfieldSec_1_2" 
                                                      name= "btnAdd"
                                                      iconName="utility:add"
                                                      class="btnIcon"
                                                      variant="brand"
                                                      onclick="{!c.ShowNextField}"
                                                      />
                                <lightning:buttonIcon aura:id="btnRemoveFieldSec_1_2" 
                                                      name= "btnRemove"
                                                      iconName="utility:close"
                                                      class="btnIcon"
                                                      variant="brand" 
                                                      onclick="{!c.hideCurrentField}"/>
                            </div>
                        </div>
                        </div>
                       
                </div>
                
                <!--Section 2-->
                
                <div class="slds-grid hideFields" aura:id="Sec_2_1">
                    <div class="slds-col slds-size_1-of-1">
                        <div class="slds-grid" aura:id="objectSec_2_1">
                            <div class="slds-col slds-size_10-of-12" style="padding:10px;" >
                                <lightning:select aura:id="ObjPicklistSec_2_1"  name="{!v.name}" label="Entity"  onchange="{!c.PopulateFieldsName}">
                                    <aura:iteration items="{!v.ObjectNames}" var="ob">
                                        <option value="{!ob}">{!ob}</option>
                                    </aura:iteration>
                                    
                                </lightning:select>
                            </div>
                            <div class="slds-col slds-size_2-of-12" style="padding-top:30px;"  >
                                
                                <lightning:buttonIcon aura:id="btnAddObjectSec_2_1" 
                                                      name= "btnAdd"
                                                      iconName="utility:add"
                                                      class="btnIcon"
                                                      variant="brand"
                                                      onclick="{!c.ShowNextObject}"
                                                      />
                                <lightning:buttonIcon aura:id="btnRemoveObjectSec_2_1" 
                                                      name= "btnRemove"
                                                      iconName="utility:close"
                                                      class="btnIcon"
                                                      variant="brand" 
                                                      onclick="{!c.hideCurrentObject}"/>
                            </div>
                        </div>
                        
                                <div class="slds-grid" aura:id="relationSec_2_1">
                            <div class="slds-col slds-size_1-of-12" style="padding:10px;" >                                
                            </div>
                            <div class="slds-col slds-size_10-of-12" style="padding:10px;" >
                                <lightning:select aura:id="relationPicklistSec_2_1"  onchange="{!c.PopulateFieldLabel}" label="Relationship">
                                    <aura:iteration items="{!v.RelationNames_2}" var="rd">
                                        <option value="{!rd}">{!rd}</option>
                                    </aura:iteration>
                                </lightning:select> 
                            </div>
                            <div class="slds-col slds-size_1-of-12" style="padding-top:30px;"  >
                            </div>
                        </div>
                        
                        <div class="slds-grid" aura:id="fieldSec_2_1">
                            <div class="slds-col slds-size_1-of-12" style="padding:10px;" ></div>
                            <div class="slds-col slds-size_10-of-12" style="padding:10px;" >
                                <lightning:select aura:id="fieldPicklistSec_2_1"  onchange="{!c.PopulateFieldLabel}" label="Field">
                                    <aura:iteration items="{!v.FieldNames_2}" var="fd">
                                        <option value="{!fd}">{!fd}</option>
                                    </aura:iteration>
                                </lightning:select> 
                            </div>
                            <div class="slds-col slds-size_1-of-12" style="padding-top:30px;"  >
                                
                                <lightning:buttonIcon aura:id="btnAddfieldSec_2_1" 
                                                      name= "btnAdd"
                                                      iconName="utility:add"
                                                      class="btnIcon"
                                                      variant="brand"
                                                      onclick="{!c.ShowNextField}"
                                                      />
                            </div>
                        </div>
                        <div class="slds-grid hideFields" aura:id="fieldSec_2_2">  
                            <div class="slds-col slds-size_1-of-12" style="padding:10px;" ></div>
                            <div class="slds-col slds-size_9-of-12" style="padding:10px;" >
                                <lightning:select aura:id="fieldPicklistSec_2_2"  onchange="{!c.PopulateFieldLabel}" label="Field">
                                    <aura:iteration items="{!v.FieldNames_2}" var="fd">
                                        <option value="{!fd}">{!fd}</option>
                                    </aura:iteration>
                                </lightning:select> 
                            </div>
                            <div class="slds-col slds-size_2-of-12" style="padding-top:30px;"  >
                                
                                <lightning:buttonIcon aura:id="btnAddfieldSec_2_2" 
                                                      name= "btnAdd"
                                                      iconName="utility:add"
                                                      class="btnIcon"
                                                      variant="brand"
                                                      onclick="{!c.ShowNextField}"
                                                      />
                                <lightning:buttonIcon aura:id="btnRemoveFieldSec_2_2" 
                                                      name= "btnRemove"
                                                      iconName="utility:close"
                                                      class="btnIcon"
                                                      variant="brand" 
                                                      onclick="{!c.hideCurrentField}"/>
                            </div>
                        </div>
                        
                      
                    </div>
                </div>              
                
                    
                </div>
                
            </div>
            <div class="slds-col slds-size_1-of-1 slds-small-size_1-of-2 slds-medium-size_1-of-2" style="border:1px solid #cacaca;">
                <div class="slds-grid" style="border:1px solid #cacaca;">
                    
                    <div class="slds-col slds-size_4-of-12">
                        <div style="float:left;margin-left:10px;">
                            <lightning:input type="text" name="CCRLabel" placeholder="101" aura:id="CCRLabel" value="{!v.jsonLabel}" />
                        </div>
                        
                    </div>
                    <div class="slds-col slds-size_4-of-12">
                        <br/><center><b>Json Viewer</b></center>
                        
                    </div>
                    <div class="slds-col slds-size_4-of-12">
                        
                        <div class="slds-grid" >
                            
                            <div class="slds-col slds-size_4-of-12">
                                 <div style="float:right;margin:10px;">
                                    <lightning:button aura:id="btnLoadJson" 
                                                      label= "Load"                                                     
                                                      variant="brand" 
                                                      onclick="{!c.LoadJson}"/>
                                </div>
                            </div>
                            <div class="slds-col slds-size_4-of-12">
                                <div style="float:right;margin:10px;">
                                    <lightning:button aura:id="btnClearJson" 
                                                      label= "New"                                                     
                                                      variant="brand" 
                                                      onclick="{!c.clearJson}"/>
                                </div>
                            </div>
                            <div class="slds-col slds-size_4-of-12">
                                <div style="float:right;margin:10px;">
                                    <lightning:button aura:id="btnSaveJson" 
                                                      label= "Save"                                                     
                                                      variant="brand" 
                                                      onclick="{!c.SaveJson}"/>
                                </div>
                            </div>
                            
                        </div>
                        
                        
                        
                        
                    </div>
                </div>
                
                <div class="slds-grid">
                    <div class="slds-col slds-size_11-of-12" style="margin:10px;min-height:400px;word-wrap: break-word;padding:10px;">
                        {!v.finalJsonString}                         
                    </div>
                </div>
            </div>
        </div>    
    </div> 
</aura:component>

Step 3: Create JsonCreatorCmpController.js and copy paste below code

({
    doInit : function(component, event, helper) {    
        helper.getObjectApiNameList(component, event);
    },
    ReqTypechange :function(component, event, helper) 
    {
        var delButtonPress= event.getSource().getLocalId();
    },
    PopulateFieldsName:function(component,event,helper)
    {
        
        component.set("v.loaded",true);
        var objPicklistAuraId= event.getSource().getLocalId(); 
        var array=objPicklistAuraId.split('_');
        var arr1=array[1];
        
        component.set("v.FieldNames_'"+arr1+"'", null);                
        component.set("v.RelationNames",null);
        
        helper.GetFieldNameByObject(component,event,objPicklistAuraId);
        helper.GetRelationShipByObject(component,event,objPicklistAuraId);
        helper.GenerateJson(component,event);
        //$A.enqueueAction(component.get("c.GenerateJson"));
    },
    ShowNextField:function(component,event,helper)
    {
        
        var fieldpicklistAuraId= event.getSource().getLocalId();   
        var array=fieldpicklistAuraId.split('_');
        var arr1=array[1];
        var arr2=parseInt(array[2]);
        var addVal=1;
        var lastAppendVal=arr2+addVal;
        //var lstChar= picklistId.charAt(picklistId.length-1);
        var cmpauraid = "fieldSec_"+array[1]+'_'+lastAppendVal;
        var cmpTarget = component.find(cmpauraid);
        $A.util.removeClass(cmpTarget, 'hideFields');
        
    },
    ShowNextObject:function(component,event,helper)
    {
        
        var objectpicklistAuraId= event.getSource().getLocalId();   
        var array=objectpicklistAuraId.split('_');
        var arr1=parseInt(array[1]);
        var arr2=parseInt(array[2]);
        var addVal=1;
        var lastAppendVal=arr1+addVal;
        //var lstChar= picklistId.charAt(picklistId.length-1);
        var cmpauraid = "Sec_"+lastAppendVal +'_'+ array[2];
        var cmpTarget = component.find(cmpauraid);
        $A.util.removeClass(cmpTarget, 'hideFields');
        
    },
    hideCurrentField:function(component,event,helper)
    {
        debugger;
        var fieldpicklistAuraId= event.getSource().getLocalId();   
        var array=fieldpicklistAuraId.split('_');
        var arr1=array[1];
        var arr2=parseInt(array[2]);
        var addVal=1;
        var lastAppendVal=arr2;
        //var lstChar= picklistId.charAt(picklistId.length-1);
        var cmpauraid = "fieldSec_"+array[1]+'_'+lastAppendVal;
        var cmpTarget = component.find(cmpauraid);
         component.find(cmpauraid).set("v.value",'--Select--');
        $A.util.addClass(cmpTarget, 'hideFields');
        
        helper.GenerateJson(component,event);
         //$A.enqueueAction(component.get("c.GenerateJson"));
        
    },
    hideCurrentObject:function(component,event,helper)
    {       
        var objectpicklistAuraId= event.getSource().getLocalId();   
        var array=objectpicklistAuraId.split('_');
        var arr1=parseInt(array[1]);
        var arr2=parseInt(array[2]);
        var addVal=1;
        var lastAppendVal=arr1
        //var lstChar= picklistId.charAt(picklistId.length-1);
        var cmpauraid = "Sec_"+lastAppendVal +'_'+ array[2];
        var cmpTarget = component.find(cmpauraid);
       
        $A.util.addClass(cmpTarget, 'hideFields');
        
        helper.GenerateJson(component,event);
        // $A.enqueueAction(component.get("c.GenerateJson"));
    },
    PopulateFieldLabel:function(component,event,helper)
    {
        component.set("v.loaded",true);
        var fieldPicklistAuraId=event.getSource().getLocalId();
        //helper.GetFieldLabelByFieldName(component,event,fieldPicklistAuraId); 
        helper.GenerateJson(component,event);
        component.set("v.loaded",false);
        //$A.enqueueAction(component.get("c.GenerateJson"));
    },
    getCurrentField:function(component,event,helper)
    {
        debugger;
        var btnAuraId=event.getSource().getLocalId();
        var array=btnAuraId.split('_');
        var cmpAuraId=component.get("v.myInput");
        var inputVal=component.find(cmpAuraId+'_'+array[1]).get("v.value");
    },
    SaveJson : function(component,event,helper)
    {
        helper.SaveJsonIntoCustomMetadata(component,event);
        
    },
    clearJson : function(component,event,helper)
    {
       component.set("v.loaded",true);
       //component.set("v.finalJsonString","");
       // helper.getObjectApiNameList(component,event);
       $A.get('e.force:refreshView').fire();  
        //component.set("v.loaded",false);      
    },
    LoadJson : function(component,event,helper)
    {
        helper.LoadJsonFromMeta(component,event);
    }
    
})

Step 4 : Create JsonCreatorCmpHelper.js and copy paste below code

({
    getObjectApiNameList : function(component,event) {
        var action=component.get("c.getObjectApiNames");
        action.setCallback(this, function(response){
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS"){
                component.set("v.ObjectNames", response.getReturnValue());
             
                component.set("v.loaded",false);
            }
            else if(state === "ERROR"){
                var errors = response.getError();
                if(errors) {
                    if(errors[0] && errors[0].message){
                        console.log("Error message: " + errors[0].message);
                    }
                    else{
                        console.log("unknown error");
                    }
                }
            }
                else if(state === "INCOMPLETE"){
                    console.log("Incomplete action. The server might be down or the client might be offline.");
                }
        });
        $A.enqueueAction(action);
    },
    
    GetFieldNameByObject: function(component,event,objPicklistAuraId) {
        var array=objPicklistAuraId.split('_');
        var arr1=array[1];
        
        var objArray = component.find(objPicklistAuraId).get("v.value").split('[');             
        
        var action=component.get("c.GetFieldNameByObjectName");
        
        action.setParams({
            "objName": objArray[1].substring(0,objArray[1].length - 1)       
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS"){
                
                if(arr1=="1")
                {
                    component.set("v.FieldNames_1", response.getReturnValue());
                }
                if(arr1=="2")
                {
                    component.set("v.FieldNames_2", response.getReturnValue());
                }
                
                
                 component.set("v.loaded",false);
            }
            else if(state === "ERROR"){
                var errors = response.getError();
                if(errors) {
                    if(errors[0] && errors[0].message){
                        console.log("Error message: " + errors[0].message);
                    }
                    else{
                        console.log("unknown error");
                    }
                    component.set("v.FieldNames", null);
                }
            }
                else if(state === "INCOMPLETE"){
                    console.log("Incomplete action. The server might be down or the client might be offline.");
                    component.set("v.FieldNames", null);
                }
        });
        $A.enqueueAction(action);
        
    },
    
     GetRelationShipByObject: function(component,event,objPicklistAuraId) {
        var array=objPicklistAuraId.split('_');
        var arr1=array[1];
        var objArray = component.find(objPicklistAuraId).get("v.value").split('[');
        var action=component.get("c.getRelationShipNameByObjectApiName");
        action.setParams({
            "objApiName": objArray[1].substring(0,objArray[1].length - 1)       
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS"){
                //component.set("v.RelationNames", response.getReturnValue());
                 if(arr1=="1")
                {
                    component.set("v.RelationNames_1", response.getReturnValue());
                }
                if(arr1=="2")
                {
                    component.set("v.RelationNames_2", response.getReturnValue());
                }
               
                component.set("v.loaded",false);
            }
            else if(state === "ERROR"){
                var errors = response.getError();
                if(errors) {
                    if(errors[0] && errors[0].message){
                        console.log("Error message: " + errors[0].message);
                    }
                    else{
                        console.log("unknown error");
                    }
                    component.set("v.RelationNames", null);
                }
            }
                else if(state === "INCOMPLETE"){
                    console.log("Incomplete action. The server might be down or the client might be offline.");
                    component.set("v.RelationNames", null);
                }
        });
        $A.enqueueAction(action);
        
    },
 
    GetFieldLabelByFieldName:function(component,event,fieldPicklistAuraId)
    {
        debugger;
        var array=fieldPicklistAuraId.split('_');
        var arr1=array[1];
        var arr2=array[2];
        
        var selObjName = component.find("ObjPicklistSec_"+arr1+"_1").get("v.value");       
        var selFieldName = component.find(fieldPicklistAuraId).get("v.value");
        
        var action=component.get("c.GetFieldLabel");
        action.setParams({
            "objName":selObjName,
            "fieldName":selFieldName
        });   
        action.setCallback(this, function(response){
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS"){
                component.find("LabelNames_"+arr1+"_"+arr2).set("v.value",response.getReturnValue());
                this.GenerateJson(component,event);
                 component.set("v.loaded",false);
            }
        });
        $A.enqueueAction(action);
    },
    GenerateJson:function(component,event)
    { 
        component.set("v.finalJsonString"," ");
        var initJson="[";
        var endJson="]";
        var initFieldJson='"fields":[';
        var endFieldJson="]";
        var finalJson="";
        var objJson="";
        var relJson="";
        
        var arrayJson=[];
        
        for(var j=1;j<21;j++)
        {
            var Sec = component.find("Sec_"+ j +"_"+ 1);
            var isSecNeedToCheck = $A.util.hasClass(Sec, "hideFields");
            if(!isSecNeedToCheck)
            {
                var objCmpSecVal = component.find("ObjPicklistSec_"+ j +"_"+ 1).get("v.value");
                if(objCmpSecVal !== '--Select--' && objCmpSecVal !== '')
                {
                    var entityArr = objCmpSecVal.split('[');
                    
                    objJson = ',{"entity":"'+ entityArr[1].substr(0,entityArr[1].length - 1) +'",';
                    
                    var relationshipname = component.find("relationPicklistSec_"+ j +"_"+ 1).get("v.value");                                            
                    if(relationshipname !== '--Select--' && relationshipname !== '')
                    {   
                        relJson = '"relationship": "'+ relationshipname +'",';
                    }
                    if(relationshipname == '--Select--' ||  relationshipname == '')
                    {
                        relJson = '"relationship": "'+ ' ' +'",';
                    }
                    
                    var fldJson="";
                    for(var k=1;k<21;k++)
                    {
                        var fldSec = component.find("fieldSec_"+ j +"_"+ k);                
                        var isfldNeedToCheck= $A.util.hasClass(fldSec, "hideFields");
                        if(!isfldNeedToCheck)
                        {
                            var fldCmpSecVal = component.find("fieldPicklistSec_"+ j +"_"+ k).get("v.value");
                           // var fldLabel=component.find("fieldPicklistSec_"+ j +"_"+ k).get("v.value");
                            if(fldCmpSecVal !== '--Select--' && fldCmpSecVal !== '')
                            {                                    
                                fldJson = fldJson + '{"name":"'+fldCmpSecVal.split('[')[1].substr(0,fldCmpSecVal.split('[')[1].length - 1) +'","label":"'+ fldCmpSecVal.split('[')[0] +'"},';
                            }
                        }
                    }
                    if(fldJson !== ''){
                        fldJson = initFieldJson + fldJson.substring(0, fldJson.length-1) + endFieldJson;                          
                    }
                    arrayJson.push(objJson + relJson + fldJson +"}");
                    // finalJson = finalJson + objJson + fldJson;
                }
                
            }
        }
        
        /*  arrayJson.forEach(function(el){
           finalJson = finalJson + el;
        });*/
        for(let m=0;m<arrayJson.length;m++)
        {
            if(m==0)
            {
                arrayJson[m]=arrayJson[m].substr(1);
            }
            finalJson = finalJson + arrayJson[m];
        }
        finalJson = initJson + finalJson + endJson;
        component.set("v.finalJsonString",finalJson);
         //component.set("v.loaded",false);
    },
    SaveJsonIntoCustomMetadata:function(component,event)
    {
        var jsonVal=component.get("v.finalJsonString");
        var jsonLabel=component.get("v.jsonLabel");
        if($A.util.isEmpty(jsonLabel))
        {
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "Required!",
                "message": "Please enter Label",
                "type" : 'error',
            });
            toastEvent.fire(); 
            component.find("CCRLabel").set("v.class","required");
        }
        else
        {       
            if($A.util.isEmpty(jsonVal))
            {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Required!",
                    "message": "Please select Entity and Field to populate Json Value",
                    "type" : 'error',
                });

            }
            else{
                
                var action=component.get("c.SaveCCRDataElements");
                action.setParams({
                    "jsonValue" : jsonVal,
                    "jsonLabel" : jsonLabel
                });
                action.setCallback(this,function(response){
                    var state = response.getState();
                    if(component.isValid() && state === "SUCCESS"){            
                        // component.set("v.FieldNames_1", response.getReturnValue());    
                        var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                            "title": "Success!",
                            "message": "The record has been saved successfully. please check after some time",
                            "type" : 'success',
                        });
                        toastEvent.fire();       
                    }
                });
                
                $A.enqueueAction(action);
            }
        }
        
    },
    LoadJsonFromMeta:function(component,event)
    {
        
        var jsonLabel=component.get("v.jsonLabel");
        if($A.util.isEmpty(jsonLabel))
        {
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "title": "Required!",
                "message": "Please enter Label",
                "type" : 'error',
            });
            toastEvent.fire(); 
            component.find("CCRLabel").set("v.class","required");
        }
        else
        { 
            component.set("v.loaded",true);
            var action=component.get('c.getJsonFromMetadata');
            action.setParams({
                'jsonlabel':jsonLabel
            });
            action.setCallback(this,function(response){
                if(response.getState()=='SUCCESS' && !$A.util.isUndefinedOrNull(response.getReturnValue))
                {
                    component.set('v.finalJsonString',response.getReturnValue());
                    component.set("v.loaded",false);
                }
                else
                {
                    component.set("v.loaded",false);
                    component.set('v.finalJsonString',null);
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        "title": "Information",
                        "message": "No Json is available for CCRLabel: " + jsonLabel,
                        "type" : 'info',
                    });
                    toastEvent.fire(); 
                }
                
            });
            $A.enqueueAction(action);
        }
       
    }
})

Step 5: Create JsonCreatorController.cls class and copy paste below code

public class JsonCreatorController {
    
    @AuraEnabled
    public static List<String> getObjectApiNames() {
       /* Map<string,Schema.SObjectType> s = Schema.getGlobalDescribe();
        List<String> objNames=new List<String>();
        objNames.add('--Select--');
        for(String objName : s.keySet()){
            
            DescribeSObjectResult describe = SObjectType.objName;
            system.debug(describe.getLabel());
            
            objNames.add( objName);            
        } 
		objNames.sort();
        return objNames;

	*/
        
        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();        
        List<String> objNames=new List<String>();
         objNames.add('--Select--');
        for(Schema.SObjectType f : gd)
        {          
            objNames.add(f.getDescribe().getLabel() + ' [' + f.getDescribe().getName() + ']');            
        }     
        objNames.sort();
        return objNames;
    }
    @AuraEnabled
    public static List<String> GetFieldNameByObjectName(String objName)
    {
        Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
        Schema.SObjectType sobjType = gd.get(objName); 
        Schema.DescribeSObjectResult describeResult = sobjType.getDescribe(); 
        Map<String,Schema.SObjectField> fieldsMap = describeResult.fields.getMap(); 
        List<String> fieldNames=new List<String>();
         for(String fieldName : fieldsMap.keySet()){
            fieldNames.add(fieldsMap.get(fieldName).getDescribe().getLabel() +' ['+ fieldName +']');            
        }
        fieldNames.add('--Select--');
        fieldNames.sort();
		return fieldNames;
    }
    @AuraEnabled
    public static String GetFieldLabel(String objName, String fieldName)
    {
      return  Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap().get(fieldName).getDescribe().getLabel();
    }
    @AuraEnabled
    public static void  SaveCCRDataElements(String jsonValue,String jsonLabel)
    {
        Map<String, Object> metadataFieldValueMap = new Map<String, Object>();
        metadataFieldValueMap.put('DataElementObject__c', jsonValue);        
        //metadataFieldValueMap.put('Name', System.Label.CCRLabel+jsonLabel);
        CustomMetadataUtils.createCustomMetadata('ECX_CCRDataElements__mdt', jsonLabel , metadataFieldValueMap);
    }
    @AuraEnabled
    public static List<String> getRelationShipNameByObjectApiName(String objApiName)
    {
       system.debug('===objApiName==='+objApiName);
        
        Set<String> relationShipName=new Set<String>();
        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();        
        
        for(Schema.SObjectType f : gd)
        {          
            for (ChildRelationship relation : f.getDescribe().getChildRelationships())
            {
                if(String.valueOf(relation.getChildSObject()) == objApiName)
                {
                    if (relation.getRelationshipName() != null)
                    {                        
                        relationShipName.add(relation.getRelationshipName());
                    }
                }
            }
        }
        system.debug('===relationShipName==='+relationShipName);
        List<String> rellstName=new List<String>(relationShipName);
        rellstName.add('--Select--');
        rellstName.sort();
        return rellstName;
    }
    
    @AuraEnabled
    public static String getJsonFromMetadata(String jsonlabel)
    {
        ECX_CCRDataElements__mdt ccrdataelementMDT=[select Id,Label,DataElementObject__c from ECX_CCRDataElements__mdt 
                                                    where Label =:jsonLabel limit 1];
        if(ccrdataelementMDT != null)
        return ccrdataelementMDT.DataElementObject__c;
        else
            return null;
    }
}

Step 6: Create CustomMetadataUtils.cls apex class and copy paste below code

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.fullName = metdataName + '.' + System.Label.CCRLabel+label;
        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 = Test.isRunningTest() ? '00B28000005XQW6' : Metadata.Operations.enqueueDeployment(mdContainer, callback);
        //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 = Test.isRunningTest() ? '00B28000005XQW6' : Metadata.Operations.enqueueDeployment(mdContainer, callback);
    }

}

Step 7: Create JsonCreatorControllerTest.cls test class and copy paste below code

@isTest
public class JsonCreatorControllerTest {
    /*Avinash */
    static testmethod void test1()
    {
        Test.startTest();
        JsonCreatorController.getObjectApiNames();
        JsonCreatorController.GetFieldNameByObjectName('Account');
        JsonCreatorController.GetFieldLabel('Account','Name');
        String jsonVal='[{"entity":"APIToken__c","relationship": "APITokensMy__r","fields":[{"name":"accountid__c","label":"Account "}]}]';
        String jsonLabel='101';
        JsonCreatorController.SaveCCRDataElements(jsonVal,jsonLabel);
        JsonCreatorController.getRelationShipNameByObjectApiName('Account'); 
        JsonCreatorController.getJsonFromMetadata('101');
        Test.stopTest();
    }

}