Sub topic 2
Navigating to Record and Object Pages
Assume you know basic Lightning Web Components structure, @api, event handling, and JavaScript async/await. You should also know that a Salesforce record has an ID and belongs to an object such as Account or Contact.
Navigating with `NavigationMixin`
A PageReference is a JavaScript object that describes a Salesforce page. NavigationMixin adds navigation methods to your component. Use Navigate with a page reference instead of hard-coding URLs.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class AccountActions extends NavigationMixin(LightningElement) {
@api recordId;
viewAccount() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
openAccounts() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'home'
}
});
}
}standard__recordPage supports actions such as view, edit, and clone. standard__objectPage supports actions such as home, list, and new.
Other page types include:
standard__namedPagefor pages such ashomestandard__webPagewith a URL attributestandard__appfor an app pagestandard__navItemPagewith a custom navigation item API name
URLs, state, and current pages
Use GenerateUrl when you need an anchor link instead of immediate navigation. It returns a Promise containing the platform-generated URL.
const pageRef = {
type: 'standard__recordPage',
attributes: { recordId: this.recordId, actionName: 'view' }
};
this[NavigationMixin.GenerateUrl](pageRef).then((url) => {
this.recordUrl = url;
});A page reference can include state, which contains URL parameters. State keys must use a namespace, such as c__filter. List views use filterName. New-record pages can use defaultFieldValues, encoded with encodeDefaultFieldValues from lightning/pageReferenceUtils.
CurrentPageReference reads the current page and updates when navigation changes.
import { wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
@wire(CurrentPageReference)
pageReference;LightningModal basics
LightningModal provides a reusable modal dialog. A modal class extends LightningModal, and another component opens it with the modal class's static open method.
The modal template normally uses a header, body, and footer:
<template>
<lightning-modal-header label="Confirm delete"></lightning-modal-header>
<lightning-modal-body>
<p>Delete this record?</p>
</lightning-modal-body>
<lightning-modal-footer>
<lightning-button label="Cancel" onclick={handleCancel}></lightning-button>
<lightning-button variant="destructive" label="Delete" onclick={handleDelete}></lightning-button>
</lightning-modal-footer>
</template>Exercise
Which API should you use to open an Account record immediately?
Show answer
Use NavigationMixin.Navigate with a standard__recordPage page reference and actionName: 'view'.