Navigate to Record Page in Salesforce Lightning Web Component : Bijay Kumar

Navigate to Record Page in Salesforce Lightning Web Component
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Salesforce NavigationMixin in Lightning Web Components In Salesforce, you can create records for both custom and standard objects using Lightning Web Components (LWC). After creating a record, users typically navigate to the object tab to view it. However, to streamline this process, Salesforce provides the **NavigationMixin** feature, which allows users to navigate directly to the record page immediately after creation. #### What is NavigationMixin? **NavigationMixin** is a feature in Salesforce that enables navigation between different Lightning pages, records, and components. It utilizes two main functions: 1. **Navigate**: This function allows navigation to various pages (like record pages) by providing a PageReference object that includes details such as recordId or objectApiName. - **Syntax**: `this[NavigationMixin.Navigate]` 2. **GenerateURL**: This function creates a URL for a specific page and returns it as a promise, allowing for asynchronous handling of the URL. - **Syntax**: `this[NavigationMixin.GenerateURL]` #### Example Use Cases 1. **Navigating to a Record Page After Creation**: - A Lightning web component can be created to allow users to input an account name and save it. Upon successful creation, the component navigates to the newly created account's detail page using the `NavigationMixin.Navigate` method. 2. **Generating URLs for Related Records**: - For displaying a list of related contacts, the `NavigationMixin.GenerateURL` method can be used to create a link for each contact. When a user clicks the link, it opens the contact's record page in a new tab. ### Implementation Steps 1. **Creating a Lightning Web Component**: - Define the component's JavaScript and HTML files to handle user input and display the UI. - Use the `createRecord` function to save the account and navigate to its detail page. 2. **Using Apex for Related Records**: - Create an Apex class to fetch related contacts based on the current account ID. - Use the `@wire` decorator to retrieve contacts and generate URLs for navigation. 3. **Meta Configuration**: - Ensure the component is exposed to the appropriate Lightning pages (App, Record, Home) in the `meta.xml` file. ### Conclusion By utilizing the **NavigationMixin** in Salesforce Lightning Web Components, developers can enhance user experience by simplifying navigation processes. This feature allows for seamless transitions between record creation and viewing, as well as easy access to related records. ### Additional Information For further learning, consider exploring: - How to add Lightning Web Components as custom tabs in Salesforce. - Creating quick actions with Lightning Web Components. - Implementing custom validation in Salesforce Lightning Web Components. ### Hashtags for SEO #Salesforce #LightningWebComponents #NavigationMixin #SalesforceDevelopment #LWC #SalesforceTutorial #Apex #WebDevelopment #CRM #UserExperience


In Salesforce, we can create records using Lightning Web Components for custom and standard objects. After creating a record, to view it, we have to navigate to the object tab and then select the created record from the object list view.

To avoid moving from one tab to another just to view the record page, we can use the NavigationMixin feature in the Lightning web component . It would be easy for the user if the record page opened just after creating the record.

In this Salesforce tutorial, we will learn how to navigate to the record page in Salesforce Lightning web component using the NavigationMixin feature.

What is NavigationMixin in Salesforce Lightning Web Components?

In Salesforce, the NavigationMixin feature allows navigation between different Lightning pages (record page, app page, and home page), records, and components within the Lightning pages. The NavigationMixin feature uses two APIs for navigation: Navigate and GenerateURL.

The Navigate function helps us navigate to different pages in Salesforce. We need to provide a PageReference object that defines on which page the user will be navigated (like a record page, object page, or custom page). It also includes information like the recordId or objectApiName, depending on the page we are navigating on.

Syntax:

(this[NavigationMixin.Navigate]) 

The GenerateURL function creates a URL for a page and returns it as a promise. This allows us to handle the URL asynchronously, ensuring that the page is only accessed once the URL is fully generated.

The resulting URL can be used in the href attribute of an <a> tag to navigate to the page or passed to window.open() to open the page in a new window or tab.

Syntax:

this[NavigationMixin.GenerateURL]

In the below example, we will see the use case of both navigation methods for navigation in the lightning web component.

Navigate to the Record Page in Lightning Web Component using NaivgationMixin.Navigate

In this example, we will create a Lightning web component, which we can use to create an account record. Using NaivgationMixin.Navigate function, the user will be navigated to the created account record detail page.

Follow the steps below to create a Lightning web component with the navigation feature.

  1. Create a Lightning Web ComponentredirectToRecordPage, and enter the code below in the JS file. This code defines the logic for creating an account and navigating to the account’s record page.

Here, we have imported the navigation feature using the import { NavigationMixin } from ‘lightning/navigation’.

To navigate to the record detail page, we have defined a method navigateToRecord(), in which we have used the NavigationMixin. In this, we have type as “standard_recordPage“, so that it navigates to the standard account record page.

The actionName set as ‘view‘ will open the record page in view mode.

import { LightningElement, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
import accObj from '@salesforce/schema/Account';
import nameFld from '@salesforce/schema/Account.Name';

export default class RedirectToRecordPage extends NavigationMixin(LightningElement) {
    @track accountName;
    @track accountId;

    handleNameChange(event) {
        if (event.target.name == 'accountName') {
            this.accountName = event.target.value;
        }
    }

    navigateToRecord() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.accountId,
                actionName: 'view'
            }
        });
    }

    saveAction() {
        const fields = {};
        fields[nameFld.fieldApiName] = this.accountName;
        const accRecordInput = { apiName: accObj.objectApiName, fields };
        createRecord(accRecordInput)
            .then(account => {
                this.accountId = account.id;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Account created',
                        variant: 'success',
                    })
                );
                this.navigateToRecord();
                this.accountId = '';
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    })
                );
            });
    }
}

In the above code, we have defined properties accountName and accountId to store user input and the newly created record’s ID. When a user enters an Account name, the handleNameChange method stores the input.

On clicking save, the saveAction method calls createRecord from the lightning/uiRecordApi to create the Account. If successful, a success toast notification appears, and the navigateToRecord method navigates to the record page using NavigationMixin.

  1. Enter the code below in the HTML file to define the UI of the LWC. In this, we will add an input field to enter the account name and a save button to create the record.
<template>
    <lightning-card title="Create Account In LWC" icon-name="standard:account">
                <lightning-input 
                    label="Name"
                    onchange={handleNameChange}
                    value={accountName}
                    name="accountName"
                    class="slds-m-bottom_x-small">
                </lightning-input>
            </div>

                <lightning-button 
                    label="Save"
                    variant="brand"
                    onclick={saveAction}>
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>
  1. Make the component exposed to the lightning pages using the code below in the meta.xml file inside the <LightningComponentBundle> tag.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Navigate to the Lightning page and add the Lightning Web Component to the page. In the LWC, when the user enters the Account Name and clicks save, then the record will be created.

After successful record creation, it will navigate to the record detail page of the created account using the record ID.

Navigate to record detail page in Salesforce LWC

This way, we can use the NaivgationMixin.Navigate method to navigate to the record detail page of an object record.

Navigate to the Record Page in Lightning Web Component using NavigationMixin.GenerateURL

Let’s take an example, where we have a custom related list of Contacts in the Account object. For each contact, you want to show a “View” link that opens the Contact’s record page in a new tab.

For this, we don’t need to hard-code the contact record URL. Instead, we can use NavigationMixin.GenerateURL to navigate to the contact records.

Follow the steps below to navigate to the record page using NavigationMixin.GenerateURL in LWC.

  1. In this example, we are adding navigation to the related contacts of the Account. For this, we need to create an apex method that fetches the contacts using the current account ID.

Create an apex class and enter the below code to fetch the related contacts.

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts(Id accountId) {
        return [SELECT Id, Name FROM Contact WHERE AccountId = :accountId];
    }
}
  1. After this, create a Lightning Web Component in which we will display the contacts related list of the current account.

Enter the code below in the LWC’s JS file to define the navigation logic. In this, we have imported the records from the controller class and then the NavigationMixin.

The @api decorator will fetch the ID of the current account record to return its related list.

import { LightningElement, api, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import getContacts from '@salesforce/apex/ContactController.getContacts';

export default class ContactRelatedList extends NavigationMixin(LightningElement) {
    @api recordId;
    contacts;

    @wire(getContacts, { accountId: '$recordId' })
    async wiredContacts({ error, data }) {
        if (data) {
            const contactWithUrls = await Promise.all(
                data.map(async contact => {
                    const url = await this[NavigationMixin.GenerateUrl]({
                        type: 'standard__recordPage',
                        attributes: {
                            recordId: contact.Id,
                            objectApiName: 'Contact',
                            actionName: 'view'
                        }
                    });
                    return { ...contact, url };
                })
            );

            this.contacts = contactWithUrls;
        } else if (error) {
            console.error(error);
        }
    }
}

To navigate on the related contacts, a URL link will be generated using NavigationMixin.GenerateUrl. As we click URL it will navigate to contact using the record id and open the contact record detail page in the view mode.

  1. Now, enter the code below in the HTML to define the UI of the related list. In the related list, there will be a hyperlink View adjacent to each contact. As we click on View, it will navigate to contact record detail page using the target {contact.url}.
<template>
    <lightning-card title="Contacts for Account">
        <template if:true={contacts}>
            <template for:each={contacts} for:item="contact">
                <div key={contact.Id} class="slds-p-around_small">
                    {contact.Name}
                    <a href={contact.url} target="_blank" style="margin-left: 10px;">View</a>
                </div>
            </template>
        </template>
    </lightning-card>
</template>
  1. To make this component available for the account record page, enter the below code in the meta.xml file inside the <LightningComponentBundle> tag.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Account</object>
            </objects>
        </targetConfig>
    </targetConfigs>

To restrict this LWC for Account object we have set target object as in target configuration (targetConfig targets) as Account.

  1. To deploy the LWC, navigate to the account record page. Click on the settings icon and select Edit Page.
Generate URL to navigate in Salesforce LWC
  1. In the Lightning app builder, drag and drop the created LWC from Components to the page region and save the changes.
Navigate to related records page in Lightning web components

Now, on the Account record page, as we click on the View adjacent to the related contact, it will navigate to contact record page.

Navigate to related records using NavigationMixin in LWC

This way, we can navigate to the record detail page using NavigationMixin.GenerateUrl in the Lightning web components.

I hope, you understand how we can implemetn navigation in Salesforce Lightning Web Components using the NavigationMixin. In the above examples, we have learned about the use cases of Navigate and GenerateUrl navigation methods.

We used “NavigationMixin.Navigate” to navigate the record detail page. After this, using GenerateUrl, we generated a URL to navigate to the related object records.

You may also like to read:

The post Navigate to Record Page in Salesforce Lightning Web Component appeared first on SalesForce FAQs.


May 07, 2025 at 03:27PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce