Now, we will see how we can get the Salesforce Record details using Apex Class – Wiring to Property mechanism.
To do this exercise, we will try to show a Contact Record in Lightning App.
Step 1: We have created an Apex Class named “LWC_ContactController” by which we will send the Contact record to Lightning Web Component.
LWC_ContactController.cls
public with sharing class LWC_ContactController{
@AuraEnabled(cacheable = true)
public static List<Contact> getContactList(){
return [SELECT Id, Name, Email FROM Contact LIMIT 1];
}
}
getContactList() method of the Apex Class “LWC_ContactController” returns the Contact Record.
Step 2: After that, we have built a LWC named “showContactsWMP“. As per previous examples, we need to update the “showContactsWMP.js-meta.xml” file to set the visibility in Lightning App Builder.
showContactsWMP.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="showContactsWMP">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Step 3: Need to write the respective HTML file.
showContactsWMP.html
<template>
<lightning-card title="Apex Wire Method To Property">
<lightning-layout>
<lightning-layout-item flexibility="auto" padding="around-small">
<template if:true={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>
{contact.Name}
<lightning-formatted-email value={contact.Email} class="slds-m-left_medium"></lightning-formatted-email>
</p>
</template>
</template>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
Step 4: Now, we need to work on the JS file.
showContactsWMP.js
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/LWC_ContactController.getContactList';
export default class ShowContactsWMP extends LightningElement {
@wire(getContactList) contacts;
}
As per the wire method writing rules, first we have imported “getContactList” from the Apex Class, “LWC_ContactController“. Then, property contacts is wired to getContactList in this way
@wire(getContactList) contacts;
Remember, contacts is the property of wiring, that means we can get the data of contact using {contacts.data} & also we can get the error using {contacts.error} in html file and contacts is also the reactive property.
We have used wire mechanism so, the cacheable of the respective method, getContactList() of the Apex Class “LWC_ContactController” should be true.
Step 5: At last, need to add this LWC into Lightning App/Home or Record Page.
Result
9,451 total views, 12 views today









