0% found this document useful (0 votes)
220 views8 pages

Accessing Apex Class in LWC Guide

Lightning web components can call Apex methods in two ways - using wire services or imperatively. Using wire services involves annotating the Apex method with @AuraEnabled and cacheable=true, importing the method in JavaScript, and calling it using @wire. Calling imperatively directly calls the Apex method from JavaScript without @wire. The document provides examples of calling an Apex method that returns a list of contacts using wire, and calling methods to get opportunities and close an opportunity imperatively.

Uploaded by

vkrish6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
220 views8 pages

Accessing Apex Class in LWC Guide

Lightning web components can call Apex methods in two ways - using wire services or imperatively. Using wire services involves annotating the Apex method with @AuraEnabled and cacheable=true, importing the method in JavaScript, and calling it using @wire. Calling imperatively directly calls the Apex method from JavaScript without @wire. The document provides examples of calling an Apex method that returns a list of contacts using wire, and calling methods to get opportunities and close an opportunity imperatively.

Uploaded by

vkrish6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HOW TO ACCESS APEX CLASS USING LWC-

Lightning web components can import methods from Apex classes.


The imported methods are functions that the component can call
either via @wire or imperatively.

Call apex method Using Wire services.


Call the apex method imperatively.

Using Wire method:

To call the apex method in the lightning web component, First, we have to
create the apex class and add the @AuraEnabled method at the first line,
i.e., before starting the method. To call it from Wire Service, the method
should be cacheable. Hence, add cacheable=true in @AuraEnabled.
And in the LWC js controller, we need to write the import method using the
@salesforce/apex/[Link]; at the start of the js controller
and in the lightning, we need to write the @wire to get the records we
provide in the apex class.

step1: we have to create the apex class

step2 : add the @AuraEnabled method at the first line, i.e., before
starting the method.

step3: To call it from Wire Service, the method should be cacheable.


Hence, add cacheable=true in @AuraEnabled.

step4: And in the LWC js controller, we need to write the import method
using the @salesforce/apex/[Link].

step5: at the start of the js controller and in the lightning, we need to write
the @wire to get the records we provide in the apex class.

Example: Get all Contact records using wire method -


Apex Class: [Link]

public with sharing class ContactController {

@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(){
List<Contact> cons = [select id,name,phone,department,email,AccountId,birthdate from
contact];
return cons;
}
@AuraEnabled(cacheable=true)
public static List<Contact> getContactDetails(string coid){
return [select id,name,phone,department,email,AccountId,birthdate from contact where
id=:coid];

}
}

Lighting Web Component:


contactWireComponent - component

i)[Link]
<template>
<lightning-card title="Calling Apex using Wire Method">
<div class="slds-box" style="background-color:rgb(0, 255, 221) ;">
<template if:true={[Link]}>
<div class="slds-grid slds-gutters slds-wrap">
<template for:each={[Link]} for:item="co">
<div key={[Link]} class="slds-col slds-size_1-of-3
slds-p-around_small">
<lightning-card title={[Link]}>

<p>Related Account : {[Link]}</p>


<p> Phone : {[Link]}</p>
<p>Contact Email : {[Link]}</p>
<p>Department : {[Link]}</p>
<p>BirthDate : {[Link]}</p>
</lightning-card>
</div>
</template>
</div>
</template>
<template if:false={[Link]}>
<h1>error</h1>
</template>
</div>
</lightning-card>
</template>

ii)[Link]

import { LightningElement , wire} from 'lwc';


import conList from '@salesforce/apex/[Link]';
export default class ContactWireComponent extends LightningElement {
@wire(conList) cat;
}

iii)[Link]-xml

<?xml version="1.0" encoding="UTF-8"?>


<LightningComponentBundle xmlns="[Link]
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target> lightning__RecordPage </target>
<target> lightning__HomePage </target>
<target> lightning__AppPage </target>
<target> lightning__Tab </target>
</targets>
</LightningComponentBundle>

OUTPUT:
Using Imperatively method:

Calling the apex method in the lightning web component without using the
wire method is more accessible than the wire method. Making the
AuraEnabled method cacheable is not mandatory to call it imperatively.
While using the wire method, we need to add the data, but there is no need
for this in the imperatively method. It is the easiest way to call the apex
method in the LWC.

When we have combo box -> onchange event -> =


Text box -> button -> onclick -> =

Text box ->onchange event => like operator

Apex Class : [Link]

public with sharing class OpportunityController {


@AuraEnabled(cacheable=true)
public static List<Opportunity> getAllOpp(string accName){
List<Opportunity> op;
if([Link](accName)){
string str='%'+accName+'%';
op = [select
id,name,amount,StageName,closedate,LeadSource,[Link],description,isClosed,type,Ac
countId from Opportunity where [Link] like : str ];

}else{
op = [select
id,name,amount,StageName,closedate,LeadSource,[Link],description,isClosed,type,Ac
countId from Opportunity ];

}
return op;

}
// the method needs to call imperatively so it doesnt requre cacheable =true
@AuraEnabled
public static string closeOpp(String opportuityId){
string msg;

try {
Opportunity op = new Opportunity(Id=opportuityId);
[Link]='Closed Won';
update op;
msg = 'Record updated successfully..!!!';
} catch (Exception e) {
msg=[Link]();
}
return msg;
}
}

Lightning Component -
a) [Link]

<template>
<lightning-card title="Calling APEX class using Imperative Method">
<lightning-input onchange={accountHandler} label="Account Name" placeholder="Seach
Account"> </lightning-input>
<div class="slds-box">
<template if:true={[Link]}>
<div class="slds-grid slds-gutters slds-wrap slds-m-around_small"
style="background-color:rgb(4, 133, 0);">
<template for:each={[Link]} for:item="oppoObj">
<div key={[Link]} class="slds-box slds-col slds-size-1-of-2
slds-p-around_small slds-p-around_large">
<lightning-card title={[Link]}>
<div slot="actions">
<template if:true={[Link]}>
<span style="color: blue;">
Opportunity is Closed
</span>
</template>
<template if:false={[Link]}>
<lightning-button label="Close Opportunity"
variant="success" value={[Link]} onclick={opportunityHandler}></lightning-button>

</template>
</div>
</lightning-card>

<p>Account Id : {[Link]}</p>

<p>Opportunity status : {[Link]}</p>


<p>Opportunity Name : {[Link]}</p>
<p>Description : {[Link]}</p>
<p>Lead Source : {[Link]}</p>
<p>Stage Name : {[Link]}</p>
<p>Amount : {[Link]}</p>
<p>Close Date : {[Link]}</p>
<p>Type : {[Link]}</p>

</div>
</template>
</div>

</template>
<template if:false={[Link]}>
<h1>Error</h1>
</template>
</div>
</lightning-card>
</template>
b) [Link]

import { LightningElement, wire } from 'lwc';


import getOppo from '@salesforce/apex/[Link]';
import oppoClosed from '@salesforce/apex/[Link]';
import {refreshApex} from '@salesforce/apex';

export default class AccountRelatedOpportunityComponent extends LightningElement {


oppoIdj ='';
acName = '';
msg = '';

@wire (getOppo,{accName : '$acName'}) opportunities ;

accountHandler(event){
[Link] = [Link];
}

opportunityHandler(event){
[Link] = [Link];
oppoClosed({opportuityId:[Link]})
.then(result =>{
[Link] = result;
alert("message: "+[Link]);
refreshApex([Link]);
})
.catch(error=>{
[Link]=[Link];
})
}
}
c) [Link]-xml

<?xml version="1.0" encoding="UTF-8"?>


<LightningComponentBundle xmlns="[Link]
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target> lightning__RecordPage </target>
<target> lightning__HomePage </target>
<target> lightning__AppPage </target>
<target> lightning__Tab </target>
</targets>
</LightningComponentBundle>

OUTPUT:

You might also like