Skip to main content

How to use Hyperlink in Custom Toast Notification message using LWC

 Use Hyperlink in Custom Toast Notification message using LWC 


We all know that a component can send a toast notification that pops up to alert users of a success, error, or warning. A toast can also simply provide information to the user.

But what if we need a hyperlink on the message to navigate to the records on the message body. Yes, we can put Links as well on the message body as we can see in Standard Notification Toasts. This is very simple just we need to remember few things.

We should know how to use Navigation Services by using NavigationMixin.GenerateUrl method.

Let us see the functionality in this blog.

To display a toast notification in Lightning Experience or Experience Builder sites we import ShowToastEvent from the lightning/platformShowToastEvent module.

We use this ShowToastEvent to provide feedback to a user following an action, such as after a record is created.

Now in this blog we will see how to add hyperlink in the message of the Show Toast event and navigate to our desired location by clicking on it.

Lots of talking done. Let us see the implementation now.

We can add link in the following two ways.

1) By using the messageData attribute to pass in url and label values for the message string.

messageData

String[] or Object

url and label values that replace the {index} placeholders in the message string.


We can see below that index{0} is replaced with Salesforce and index{1} is replaced with here. We can also see that there a link on here.(underlined)

handleButtonClick() {
    const event = new ShowToastEvent({
        "title": "Success!",
        "message": "Record {0} created! See it {1}!",
        "messageData": [
            'Salesforce',
            {
                url: 'http://www.salesforce.com/',
                label: 'here'
            }
        ]
    });
    this.dispatchEvent(event);


2) By using the lightning/navigation module to generate the URL. In this approach we need to use NavigationMixin.GenerateUrl method to get a promise that resolves to the resulting URL.

handleRecordClick() {
    this[NavigationMixin.GenerateUrl]({
        type: 'standard__recordPage',
        attributes: {
            recordId: '003xx000000001eAAA',
            actionName: 'view',
        },
    }).then(url => {
        const event = new ShowToastEvent({
            "title": "Success!",
            "message": "Record {0} created! See it {1}!",
            "messageData": [
                'Salesforce',
                {
                    url,
                    label: 'here'
                }
            ]
        });
        this.dispatchEvent(event);
    });

}
In this the URL is generating from the NavigationMixin.GenerateUrl and we are not providing any url in the messageData.


For Demo let us take the example of my previous blog.  

In my previous blog we have implemented the ‘Add records to favorite’ where we were also showing a Toast Notification. However, we did not add the hyperlink in the toast message to directly jump to the Tab in which record was added.

Let us make a few changes in our code.

Change the entire addToFavourites.js file with below code.
import { LightningElement } from 'lwc';
import fetchRecords from '@salesforce/apex/AddToFavouritesController.fetchRecords';
import addTofavourite from '@salesforce/apex/AddToFavouritesController.addTofavourite';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';

export default class AddToFavourites extends NavigationMixin(LightningElement) {

    contactList;
    accountList;
    oppList;
    recordName;
    recorIdVal;
    error;

    connectedCallback() {
        this.fetchRecords();
    }

    fetchRecords() {
        fetchRecords()
            .then(data => {
                const wrapper = JSON.parse(data);
                if (wrapper) {
                    this.contactList = wrapper.contactList;
                    this.accountList = wrapper.accountList;
                    this.oppList = wrapper.oppList;
                    this.error = undefined;
                }
            })
            .catch(error => {
                this.contactList = undefined;
                this.accountList = undefined;
                this.oppList = undefined;
                console.log(error);
            });
    }

    addTofav(event) {
        this.recorIdVal = event.detail.recordId;
        this.recordName = event.detail.recordName;

        addTofavourite({
            recorIdVal: this.recorIdVal,
            recordName: this.recordName,
        })
            .then(data => {
                console.log(' Add To Fav 'data);
                if (data == 'Record Removed from Favourites') {
                    this.handlerrorClick();
                } else {
                    this.handleLinkClick();
                }
            })
            .catch(error => {
                console.log(error);
                const toast = new ShowToastEvent({
                    'title' : 'Error!!',
                    "message" : JSON.stringify(error),
                    "variant" : "error"
                });
                this.dispatchEvent(toast);
            });
    }

    handleLinkClick() {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Add_Favourites__c',
                actionName: 'home'
            }
        }).then(url => {
            const event = new ShowToastEvent({
                "title": "Success!",
                "message": "Record {0} added to favourites!! {1}",
                "messageData": [
                    this.recordName,
                    {
                        url,
                        label: 'View'
                    }
                ],
                "variant": "Success",
            });
            this.dispatchEvent(event);
        });
    }

    handlerrorClick() {
        const sfdcBaseURL = window.location.origin;
        console.log('sfdcBaseURL ',sfdcBaseURL);
        const event = new ShowToastEvent({
            "title": "Success!",
            "message": "Record {0} removed from favorites!! See it {1}!",
            "messageData": [
                this.recordName,
                {
                    url: sfdcBaseURL + '/lightning/o/Add_Favourites__c/home',
                    label: 'here'
                }
            ],
            "variant": "Success",
        });
        this.dispatchEvent(event);
    }
}


To check the entire code of previous blog Click here.

You can also check my Github repo for the code.

Thanks ;)
#HappyCoding.



Comments

Popular posts from this blog

How to create custom polymorphic field using LWC ?

How to create custom polymorphic field using LWC ? In this blog we will see how we can make polymorphic lookup field using LWC. What is Polymorphic field? A polymorphic field is one where related object might be one of the several different types of objects. There can be a use case where a customer wants to connect one object with multiple objects- i.e, relationships between objects or relate a child object to multiple parents's ojects. For example, in task Object we have three such polymorphic fields. The WhoId(Name) relationship of Task can be with Contact or a Lead. Assigned To field can be a User or a Queue. Similarly, a WhatId(Related To) relationship field of Task can be with many other objects like Accounts, Opportunities etc. In Salesforce, currently we do not have any OOTB option or may be we can say we do not have a datatype for polymorphic field which we can create but if required we can create a custom component to facilitate the same functionality. So let's get ...

Nested Accordion in Salesforce LWC

Are you new to LWC ? Are you wondering how to loop in and make a nested accordion in LWC.? No worries. You are are at the right place. Today in this blog we will go through this simple requirement. We will see how we can loop and use lightning-accordion in our code. Use Case: Use case is very Simple . We need to Print all Contacts which are related to a particular account . We have done this several times using different methods. But in this blog we will see how we can use map to get Account Name as Key and the related contacts as the Value. It will have learn following in this blog: How to create Key map to pull all the Account Records which has atleast one Contact in key:value fashion. How to use Wire service to pull data. How to use Lightning Accordion. Let us jump into code now. Solution : Apex Controller In this Apex Class we are fetching all Contact records and the Account Name to which it is associated. We are then creating a map of Type Map<String, List...