Sub topic 1
Showing a toast with ShowToastEvent
Prerequisites
Assume you know basic Lightning Web Components structure, @api, event handling, and JavaScript async/await. A toast is a temporary message displayed by Salesforce to give feedback about an action.
Showing a toast with ShowToastEvent
Import ShowToastEvent, create an event, and dispatch it from the component.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastDemo extends LightningElement {
handleSave() {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'The contact was saved.',
variant: 'success',
mode: 'dismissible'
})
);
}
}The variant communicates the message type:
successconfirms that an operation worked.infoprovides neutral information.warningpoints out a possible problem.errorreports a failure.
The mode controls how the toast stays visible. dismissible lets the user close it or wait for it to disappear. pester disappears after a short time and does not provide a close button. sticky remains until the user closes it.
Adding a link to a toast message
Use placeholders in message and provide their values in messageData. An object containing url and label becomes a link.
this.dispatchEvent(
new ShowToastEvent({
title: 'Record created',
message: '{0} was created. {1}',
messageData: [
'Acme Corp',
{ url: '/lightning/r/Account/001000000000001/view', label: 'Open it' }
],
variant: 'success',
mode: 'sticky'
})
);Applying NavigationMixin and calling Navigate
NavigationMixin adds navigation methods to a component. Pass Navigate a PageReference instead of constructing a Salesforce URL manually.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class OpenRecord extends NavigationMixin(LightningElement) {
@api recordId;
handleView() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
}Understanding PageReference objects
A PageReference describes a destination. Its type selects the page kind. attributes identifies that page, such as an object, record, or action. Optional state values provide URL parameters.
Exercise
Which PageReference attribute identifies the operation on a record page?
Show answer
actionName, such as view, edit, or clone.