In this post I will explain how to pass parameters from LWC to apex.
There are basically two ways to call apex from LWC.
- If you want to call the apex function onLoad of component.
- @Wire
- ConnectedCallback()
- If you want to call apex function on some other event
In both the methods there is a small difference to pass data from LWC to apex. So let's get started:
Call apex function onLoad of component :
With the help of this methods apex function call on OnLoad of component.
- Apex Class:
public class ContactInfo {
@AuraEnabled(cacheable=true)
public static List<Contact> GetInfo(String Email, String Phone)
{
List<Contact> Con = [SELECT Id, Name, Email, Phone FROM Contact
where Email =: Email and phone =: Phone];
return Con;
}
}
ContactInfo class is used in LWC component in which GetInfo method is used to return the list of contacts. @Auraenables annotation is used to access the list from apex method in LWC.
- With @Wire:
import { LightningElement,track,wire} from 'lwc';
import GetInfo from "@salesforce/apex/ContactInfo.GetInfo";
@track Mail = 'ab@gmail.com';
@track PhNum = '9876543210';
@wire(ContactInfo, { Email : '$Mail' , Phone :'$PhNum' })
Contacts(results){
if(results.data){
this.ContactData = results.data;
}
if(results.error){
this.error=results.error;
}
}
@Wire hit every time, whenever you load your LWC component. In this, parameters are passed in single quotes with $ symbol.
- With ConnectedCallback():
import { LightningElement,track,wire} from 'lwc';
import GetInfo from "@salesforce/apex/ContactInfo.GetInfo";
@track Mail = 'ab@gmail.com';
@track PhNum = '9876543210';
connectedCallback() {
ContactInfo({ Email : this.Mail, Phone : this.PhNum})
.then(results => {
this.ContactData = results;
})
.catch(error => {
this.error = error;
}
);
}
ConnectedCallback also onload of your LWC component
Call apex function on some other event :
If you want to call an apex method on any action like on click of button, then you can use this. In this apex method is called when you perform handleclick() action.
import { LightningElement,track,wire} from 'lwc';
import GetInfo from "@salesforce/apex/ContactInfo.GetInfo";
@track Mail = 'ab@gmail.com';
@track PhNum = '9876543210';
handleclick(){
ContactInfo({ Email : this.Mail, Phone : this.PhNum})
.then(results => {
this.conLists = results;
})
.catch(error => {
this.error = error;
}
);
}
Thanks,
Lovesalesforceyes
Lovesalesforceyes
No comments:
Post a Comment