The ability to navigate to a new record with default values has been added to LEX, and ready for use in both Aura and LWC components as of Spring 20, as specified in the release notes.
There is a good example that can be found in Aura documentation right now, but the LWC documentation is still missing at this point, because although referenced in the docs, the link is currently broken. Hopefully this will be addressed soon.
For now, there is a recipe in the lwc-recipes
sample app. Here is the JS code. Note use of lightning/pageReferenceUtils
to encode the default values:
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
export default class NavToNewRecord extends NavigationMixin(LightningElement) {
// below, we take an object and encode it to work with navigation
navigateToNewContactWithDefaults() {
const defaultValues = encodeDefaultFieldValues({
FirstName: 'Morag',
LastName: 'de Fault',
LeadSource: 'Other'
});
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Contact',
actionName: 'new'
},
state: {
defaultFieldValues: defaultValues // and here we set defaults as a nav parameter
}
});
}
}
One note, sfdx-lwc-jest
currently has not implemented the required package lightning/pageReferenceUtils
, so you will not be able to test without mocking this package. An issue has been raised in that repo. For now, the recipes app has left a commented-out-but-most-likely-working test in place.