Navigate to a New Record with default values in LWC
This post is going to be a little bit interesting since we will be looking at how to navigate to a new record page/form along with some default values.
We have looked at a series of posts related to Navigation in LWC.
This post is going to be a little bit interesting since we will be looking at how to navigate to a new record page/form along with some default values.
In Salesforce Classic we used to reply on URL hacking. In LWC we will be taking a separate take on them.
Here is the sample code!
<template>
<lightning-button
label="Navigate"
onclick={handleNavigation}
></lightning-button>
</template>
Let's look at the controller file that’s where all the magic happens.
import { LightningElement } from 'lwc';
//1. Import Navigation Mixin named import
import { NavigationMixin } from 'lightning/navigation';
//2. Import encodeDefaultFieldValues named import
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
export default class ExploreNewRecordNacWithDefaults extends NavigationMixin(LightningElement) {
//3. Invoke encodeDefaultFieldValues and pass the object
handleNavigation() {
//4. Object will be having filenames and values
const defaultValues = encodeDefaultFieldValues({
FirstName: 'Krishna',
LastName: 'Teja',
LeadSource: 'Web'
});
console.log(defaultValues);
//5. Invoke navigate by passing the config object
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Contact',
actionName: 'new'
},
state: {
defaultFieldValues: defaultValues
}
});
}
}
Hope this is helpful!