To launch a record’s create page with prepopulated field values we use lightning/pageReferenceUtils and lightning/navigation together.
The lightning/pageReferenceUtils module provides the encodeDefaultFieldValues() and decodeDefaultFieldValues() functions. This functions encode default field values into a string and decode them.
With standard actions, the default field values pass through the URL to the object as a string, and the redirect and replace is handled for us.
To encode the default field values into a string, pass them to encodeDefaultFieldValues(). Assign the encoded string to the state.defaultFieldValues property in the page reference.
Now, Let us take an example to "Launch a Contact Record with Default Field Values Using a Standard Action".
navToNewContactWithDefaultValues.html
<template>
<lightning-button
name="new-with-defaults"
label="Go to New Contact Record Page with Defaults"
onclick={navigateToNewContactWithDefaultValues}
></lightning-button>
</template>
navToNewContactWithDefaultValues.js
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from
'lightning/pageReferenceUtils';
export default class NavToNewContactWithDefaultValues
extends NavigationMixin(LightningElement) {
navigateToNewContactWithDefaultValues() {
const
defaultValues = encodeDefaultFieldValues({
FirstName:
'TestFName',
LastName:
'TestLName'
});
console.log(defaultValues);
this[NavigationMixin.Navigate]({
type:
'standard__objectPage',
attributes: {
objectApiName: 'Contact',
actionName: 'new'
},
state: {
defaultFieldValues: defaultValues
}
});
}
}
Now, Let us wrap our LWC comp inside aura component and place it as a standard action on contact page as shown below.
navigateToLWCAuraComp.cmp
<aura:component implements="force:lightningQuickAction">
<c:navToNewContactWithDefaultValues></c:navToNewContactWithDefaultValues>
</aura:component>
Now, click on button displayed in above image.
Contact record will be created once we click on submit button shown in above image.
With override actions, you are responsible for decoding the string of default field values from the URL.
Thanks for sharing this but an quick question, why we need nest LWC into Aura? I thought now we can use LWC in action in recently release.
ReplyDelete