How to fetch and display Custom Metadata Type records in LWC in Salesforce?

How to fetch and display Custom Metadata Type records in LWC in Salesforce?

Using Apex, we can query the Custom Metadata Type records. Using wire framework, we can call the apex class and method from Lightning Web Component and display it using lightning-datatable.

Custom Metadata Type:

Sample Code:

Apex Class:

public class SampleController {
    
    @AuraEnabled( cacheable=true )  
    public static List < Sample__mdt > fetchSampleRecs() {
        
        return [ SELECT Id, MasterLabel, Text__c FROM Sample__mdt ];
        
    }

}

Lightning Web Component:

HTML:

<template>
    <lightning-card>
        <lightning-datatable
                key-field="Id"
                data={records}
                columns={columns}
                hide-checkbox-column="true">
        </lightning-datatable>
    </lightning-card>
</template>

JavaScript:

import { LightningElement, wire } from 'lwc';
import fetchSampleRecs from '@salesforce/apex/SampleController.fetchSampleRecs';

const COLUMNS = [
    { label: 'Label', fieldName: 'MasterLabel' },
    { label: 'Text', fieldName: 'Text__c' }
];

export default class SampleLWC extends LightningElement {

    records;
    wiredRecords;
    error;
    columns = COLUMNS;
    draftValues = [];

    @wire( fetchSampleRecs )  
    wiredRecs( value ) {

        this.wiredRecords = value;
        const { data, error } = value;

        if ( data ) {
                        
            this.records = data;
            this.error = undefined;

        } else if ( error ) {

            this.error = error;
            this.records = undefined;

        }

    }  

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply