Monday, January 7, 2019

How to call apex class from lightning web components(lwc)

This post explains how to invoke an apex from lightning web components.
to import apex class methods we use @salesforce/apex scoped module

Syntax

import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
apexMethod —>The imported symbol that identifies the Apex method.
Classname —> The name of the Apex class.
Namespace —> The namespace of the Salesforce organization.
Ex:
import getAccounts from '@salesforce/apex/LWCControllerTest.getAccounts'
import saveAccount from '@salesforce/apex/LWCControllerTest.saveAccount'

Demo

LWCApexMethodDemoController.cls
public inherited sharing class LWCApexMethodDemoController {
    @AuraEnabled(Cacheable = true)
    public static List<Account> getAccounts(){
      return [SELECT Id, Name, Phone, AccountNumber, Industry, CreatedDate FROM Account ORDER BY createddate DESC  Limit 10];
    }
}

LWCApexMethodDemo.html
<template>
    <div class="slds-theme_default">
      <center>
        <p style="font-size:medium;font-family:sans-serif;padding:10px;margin:5px">Invoke Apex Method Demo</p>
        <lightning-button label="getAccounts" variant="brand" icon-name="standard:account" onclick={getallaccounts}></lightning-button>
      </center><br/><br/>

      <template if:true={Accounts}>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
          <thead>
            <tr class="slds-line-height_reset">
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="S.No">S.No</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="Account Name">Account Name</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="Phone">Phone</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="AccountNumber">AccountNumber</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="Industry">Industry</div>
              </th>
            </tr>
          </thead>
          <tbody>
            <template for:each={Accounts} for:item="acc" for:index="indexvar">
              <tr class="slds-hint-parent" key={acc.id}>
                <td data-label="S.No">
                  <div class="slds-truncate" title={indexvar}>{indexvar}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.Name}>{acc.Name}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.Phone}>{acc.Phone}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.AccountNumber}>{acc.AccountNumber}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.Industry}>{acc.Industry}</div>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </template>
    </div>
  </template>

LWCApexClassDemo.js
import {LightningElement, api, track} from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'; // import toast message event .

// import apex class and it's methods. 
import getAccounts from '@salesforce/apex/LWCApexMethodDemoController.getAccounts'

export default class LWCApexMethodDemo extends LightningElement {

    @track Accounts; // return Accounts from apex class.
    @api Account;
    @track error; // to show error message from apex controller.
    @track success; // to show succes message in ui.
    // method for get  accounts.
    getallaccounts() {
        getAccounts()
            .then(result => {
                this.Accounts = result;
                this.error = undefined;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: ' Accounts Retrieve successfully',
                        message: 'Accounts Retrieve success, no of records-->' + result.length,
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error while getting Accounts',
                        message: error.message,
                        variant: 'error',
                    }),
                );
                this.accounts = undefined;
            });
    } 
}
LWCApexClassDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="LWCApexMethodDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Result
Happy Learning!!!

2 comments:

  1. i like wireless internet because you can surf anywhere and you can avoid those ethernet cables; telecommunications call center

    ReplyDelete
  2. Pondering what web templates are? All things considered, to place it in basic terms, web templates are semi-completed, pre planned web pages that can be utilized to make and host websites in less time. free Jekyll themes

    ReplyDelete