In the previous LWCs in this area, the query to the backend lacked essential parameters that are typically required in real-world project scenarios.
<aside> 💡 Before you deep dive on this LWC, please refer to this one first LWC ApexImperativeMethod.
</aside>
<aside>
📂 You can find this LWC in this relative paths: force-app\\main\\default\\lwc\\apexImperativeMethodWithParams
</aside>
First of all, inside the ContactController
class, the method findContacts
is exposed using the @AuraEnabled(cacheable=true)
decorator.
import { LightningElement, wire } from 'lwc';
**import findContacts from '@salesforce/apex/ContactController.findContacts';**
...
This Apex method is a bit different from the previous visited on these LWC series because allows a parameter to select the name of the contact to retrieve:
@AuraEnabled(cacheable=true)
public static List<Contact> findContacts(String searchKey) {
String key = '%' + searchKey + '%';
return [
SELECT Id, Name, Title, Phone, Email, Picture__c
FROM Contact
WHERE Name LIKE :key AND Picture__c != NULL
WITH SECURITY_ENFORCED
LIMIT 10
];
}
So, in the template, the lightning-input
has a function handler attached handleKeyChange
for every key stroke that the user types in:
<lightning-input
type="search"
onchange={handleKeyChange}
label="Search"
value={searchKey}
></lightning-input>
And the handler function code is the expected one:
handleKeyChange(event) {
this.searchKey = event.target.value;
}
The invocation to the backend query is:
handleSearch() {
findContacts({ searchKey: this.searchKey })
.then((result) => {
this.contacts = result;
this.error = undefined;
})
.catch((error) => {
this.error = error;
this.contacts = undefined;
});
}
Notice that the important part is in the usage of imperative method and its associated parameters. The syntax to pass parameters is like this:
method_name({ apex_parameter_name: '$javascript_variable', apex_parameter_name2: '$javascript_variable2' })
So, in our case:
...
findContacts({ searchKey: this.searchKey })
...