Find steps to call apex method on click of a button in the salesforce lightning web component framework.
- displayContactsOnButtonClick.html – to display a button on the user interface
- displayContactsOnButtonClick.js-meta.xml – to define metadata values for a component
- displayContactsOnButtonClick.js – client-side logic to get records from server and display
- LwcController.cls – server-side logic to retrieve records
displayContactsOnButtonClick.html
<template>
<template>
<lightning-card
title="Display Contacts on click Of Button"
icon-name="custom:custom63">
<div
class="slds-m-around_medium">
<p
class="slds-m-bottom_small">
<lightning-button label="Get Contacts" onclick={handleGetContacts}></lightning-button>
</p>
<template
if:true={contacts}>
<template
for:each={contacts} for:item=cont>
<h4
key={cont.Id}>{cont.AccountId}</h4>
<h4
key={cont.FirstName}>{cont.FirstName}</h4>
<h4
key={cont.LastName}>{cont.LastName}</h4>
<h4
key={cont.Email}>{cont.Email}</h4>
</template>
</template>
<template
if:true={error}>
{errorMsg}
</template>
</div>
</lightning-card>
</template>
displayContactsOnButtonClick.js-meta.xml
<?xml version="1.0"
encoding="UTF-8"?>
<LightningComponentBundle
xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
displayContactsOnButtonClick.js
import {LightningElement,wire,track} from 'lwc';
import getContactList from '@salesforce/apex/LwcController.getContactList';
export default class
DisplayContactWhenButtonClick extends LightningElement {
@track
contacts;
@track
errorMsg;
handleGetContacts(){
getContactList()
.then(result =>{
this.contacts = result;
})
.catch(error
=>{
this.errorMsg = error;
})
}
}
LwcController.cls
public with sharing class LwcController {
// Retrive list of contact list
@AuraEnabled
public
static List<Contact> getContactList() {
return [SELECT Id,AccountId, FirstName,LastName,Email,Phone FROM Contact
limit 10];
}
}
User interface
Display records on click of a
button
You may also like
2 Comments
Hi
ReplyDeleteThanks for the information.
Just one question, why have you (in displayContactsOnButtonClick.js), imperatively called apex as well as used the wire decorator. Sorry, I am a beginner so I might be wrong, doesn't both of them used to do fetch data from Apex. Couldn't ( and why?) this work just with the imperative call.
Regards
Deepanshu
Hi Deepanshu, Thanks for checking and adding your inputs here.
DeleteThat's right, only imperative method is needed to get records on click of a button. Wired method fetches the records on load, I have removed that piece of code as it is out of context for this post. and also made some changes to the code as this was written a while ago.
Please let me know if any issues while trying this code. Thanks.