To implement toast notifications with code in Salesforce Lightning Web Components (LWC), you can follow the steps outlined below:
Step 1: Import the necessary modules
In your LWC JavaScript file, import the ShowToastEvent module from the Lightning Message Service.
import { LightningElement, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
Step 2: Display the toast notification
Within your component's JavaScript code, you can use the ShowToastEvent to display a toast notification. You can customize the toast message, title, and type based on your requirements.
// Display a success toast notification
const toastEvent = new ShowToastEvent({
title: 'Success',
message: 'Record created successfully!',
variant: 'success'
});
this.dispatchEvent(toastEvent);
Step 3: Handle different types of toast notifications
You can use different variant values to display toast notifications with different types (e.g., success, warning, error).
// Display a warning toast notification
const toastEvent = new ShowToastEvent({
title: 'Warning',
message: 'There was a problem with the operation.',
variant: 'warning'
});
this.dispatchEvent(toastEvent);
// Display an error toast notification
const toastEvent = new ShowToastEvent({
title: 'Error',
message: 'An error occurred while processing the request.',
variant: 'error'
});
this.dispatchEvent(toastEvent);
Step 4: Customize toast notification duration and other options
You can further customize the toast notification by specifying additional options such as duration, mode, and message type.
// Display a toast notification with a longer duration (10 seconds)
const toastEvent = new ShowToastEvent({
title: 'Custom Duration',
message: 'This toast notification will disappear in 10 seconds.',
variant: 'info',
mode: 'dismissable',
duration: '10000' // Duration in milliseconds
});
this.dispatchEvent(toastEvent);
Note: The dispatchEvent method is used to trigger the toast notification event.
By implementing these steps, you can easily display toast notifications in your Lightning Web Components (LWC) using code. Toast notifications provide valuable feedback to users and improve the overall user experience within your Salesforce application.