Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

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.

By Teja, ex-Salesforce engineer · Updated February 22, 2021 · 1 min read

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>

exploreNewRecordNacWithDefaults.html

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
            }
        });
    }
}

exploreNewRecordNacWithDefaults.js

Hope this is helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts