call apex method with parameters from the lightning web component in salesforce - SalesforceGlobe4U
Solution: pass list of parameters in JSON as an argument to a method as shown below
addNumbers({
n1 : this.number1,
n2 : this.number2
})
Example:
ApexClass:ApexMethodWithParameterController
public class ApexMethodWithParameterController {
@AuraEnabled
public static decimal addTwoNumbers(integer n1,integer n2) {
decimal sum = n1+n2;
return sum;
}
}
apexMethodWithParametersInLWC.html:
<template>
<lightning-card>
<div style="padding-left:5px;padding-bottom:10px"><label>Enter Number 1 </label> <input type="number" value={number1} onchange={onNumberOneFieldChange}/></div>
<div style="padding-left:5px;padding-bottom:10px"><label>Enter Number 2 </label> <input type="number" value={number2} onchange={onNumberTwoFieldChange}/></div>
<div style="padding-left:5px;padding-bottom:10px"><label>Sum is </label> <output>{sum}</output></div>
<div><input type="button" value="Calculate Sum" onclick={calculateSum}/></div>
</lightning-card>
</template>
apexMethodWithParametersInLWC.js:
import { LightningElement ,track} from 'lwc';
import addNumbers from '@salesforce/apex/ApexMethodWithParameterController.addTwoNumbers';
export default class ApexMethodWithParametersInLWC extends LightningElement {
@track sum;
@track number1;
@track number2;
onNumberOneFieldChange(event) {
this.number1 = event.target.value;
}
onNumberTwoFieldChange(event) {
this.number2 = event.target.value;
}
calculateSum() {
addNumbers({
n1 : this.number1,
n2 :this.number2
})
.then(result => {
console.log('hello');
if(result){
this.sum = result;
}
})
.catch(error => {
this.loader = false;
this.error = error;
});
}
}
apexMethodWithParametersInLWC.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
No comments:
Post a Comment