This project assumes you have completed the Trailhead project for a Hello World Lightning Web Componant, or have equivolent skills (basically I'm not reviewing how to setup your environment, connect to the org, or deploy code).
A step-by-step explination is available on my blog: https://spinningcode.org/2021/01/salesforce-lightning-web-components-with-url-parameters/
sfdx force:lightning:component:create --type lwc -n parameter_readeror use VSCode extension to generated LWC. Optionally runnpm installto get all the various JS linting and testing defaults recommended by Salesforce.- Update generated meta.xml file to match this one's
- To the start of the LWC's JS file add:
import { LightningElement, wire, track } from "lwc";
import { CurrentPageReference } from "lightning/navigation";- Setup the tracked value for the display at the top of the JS class:
@track displayValue; - Wire up the CurrentPageReference to get the value from the URL.
@wire(CurrentPageReference)
getStateParameters(currentPageReference) {
if (currentPageReference) {
const urlValue = currentPageReference.state.c__myUrlParameter;
if (urlValue) {
this.displayValue = `URL Value was: ${urlValue}`;
} else {
this.displayValue = `URL Value was not set`;
}
}
}- Update the HTML to display the value:
<template>
<div>
<lightning-card title="Url Sample" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<p>{displayValue}</p>
</div>
</lightning-card>
</div>
</template>- Deploy your code to your org.
- Go to a contact record, and edit the page. Add your new compantent to the side bar. Save and activate the page.
- Return to the record page, the component should appear and say
URL Value was not set. - In the address bar add to the end of the url:
?c__myUrlParameter=Hello, and reload the page, the compantant should now readURL Value was Hello.
- Create an APEX class called
valueReflectionwith this function:
@AuraEnabled(cacheable=true)
public static String reflectValue(String value) {
// Really you should do something useful here.
return value;
}- Create appropreiate tests, and deploy the code.
- Import the new APEX into your JavaScipt file:
import reflectValue from "@salesforce/apex/valueReflection.reflectValue"; - Update the getStateParameters handler to call the new function as a promise:
getStateParameters(currentPageReference) {
if (currentPageReference) {
const urlValue = currentPageReference.state.c__myUrlParameter;
if (urlValue) {
reflectValue({ value: urlValue })
.then((result) => {
this.displayValue = `URL Value was: ${result}`;
})
.catch((error) => {
this.displayValue = `Error during processing: ${error}`;
});
} else {
this.displayValue = `URL Value was not set`;
}
}
}- Deploy the changes, and reload your example page.