March 16, 2021

How to fetch and display Custom Metadata Types in LWC in Salesforce?

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 ];
        
    }

}

LWC:
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:


No comments:

Post a Comment