Blog

Salesforce Lightning message service in LWC

Salesforce Lightning message service in LWC

In this blog, I’ll go over a very interesting feature that lightning message service offers.

I’ll show you how to communicate between two lightning web components via the lightning message channel.

Let’s get to know about Lightning Message Channel

Consider the message channel to be a medium or a pipe through which multiple components can simultaneously serve as both publishers and subscribers and send and receive messages.

Using the Lightning message channel, you can able to communicate between Vf page, aura components, and lwc.

Salesforce Lightning message

Procedural Steps to Communicate between two Lightning Web Components

Step 1 :

Create a message channel

1. With VS Code, start a Salesforce project and then authorize your Salesforce org to use it.

2. If you used package.xml to create the project, open it and enter the following code into the types> tag to get a list of existing messaging channels.

<types>
       <members>*</members>
       <name>LightningMessageChannel</name>
</types>

3. Create a message channel with needed fields

<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>PassData</masterLabel>
    <isExposed>true</isExposed>
    <description>This is a sample Lightning Message Channel.</description>
    <lightningMessageFields>
        <fieldName>recordData</fieldName>
        <description>This is data parameter</description>
    </lightningMessageFields>
</LightningMessageChannel>

Step 2 :

Import and Publish the message channel in lwc

GetFormDetails.html

<template>
    <lightning-card title="Form Submit">
        <p class="slds-var-p-around_small">
            <lightning-input type="text" label="Name" value="{name}" onchange="{handleNameInputChange}"></lightning-input>

            <lightning-input type="email" label="Email" value="{Email}" onchange="{handleEmailInputChange}"></lightning-input>
        </p>
        <lightning-button class="slds-align_absolute-center" label="Submit" onclick="{submitForm}"> </lightning-button>
    </lightning-card>
</template>

GetFormDetails.js

import { LightningElement, wire } from "lwc";

// Import message service features required for publishing and the message channel
import { publish, MessageContext } from "lightning/messageService";
import passData from "@salesforce/messageChannel/PassData__c";
export default class GetFormDetails extends LightningElement {
    name;
    email;
    @wire(MessageContext)
    messageContext;

    handleNameInputChange(event) {
        this.name = event.target.value;
    }
    handleEmailInputChange(event) {
        this.email = event.target.value;
    }
    // Respond to UI event by publishing message
    submitForm() {
        const formData = {
            name: this.name,
            email: this.email,
        };
        const payload = { recordData: formData };
        //Publish the message channel by passing the data
        publish(this.messageContext, passData, payload);
    }
}

GetFormDetails.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Step 3 :

Subscribe and Unsubscribe from a Message Channel

ShowFormDetails.html

<template>
    <lightning-card class="" title="Form Details">
        <template if:true="{formDataList}">
            <table aria-describedby="conatact-list" class="slds-table slds-table_bordered">
                <!--Header of the table-->
                <thead>
                    <tr class="slds-line-height_reset">
                        <th class="slds-size_1-of-2" scope="col">
                            <div class="slds-truncate" title="Name">Name</div>
                        </th>

                        <th class="slds-size_1-of-2" scope="col">
                            <div class="slds-truncate" title="Email">Email</div>
                        </th>
                    </tr>
                </thead>
                <!--Body of the table-->
                <tbody>
                    <template for:each="{formDataList}" for:item="item" for:index="indexVar">
                        <tr key="{item.name}" class="slds-hint-parent">
                            <td class="slds-size_1-of-6">
                                <div>
                                    {item.name}
                                </div>
                            </td>
                            <td class="slds-size_1-of-6">
                                <div>
                                    {item.email}
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </template>
    </lightning-card>
</template>

ShowFormDetails.js

import { LightningElement, wire, track } from "lwc";
// Import message service features required for subscribing and the message channel
import { subscribe, unsubscribe, APPLICATION_SCOPE, MessageContext } from "lightning/messageService";
import recordSelected from "@salesforce/messageChannel/PassData__c";
export default class ShowFormDetails extends LightningElement {
    subscription = null;
    @track formDataList = [];
    @wire(MessageContext)
    messageContext;
    // Encapsulate logic for Lightning message service subscribe and unsubsubscribe
    subscribeToMessageChannel() {
        if (!this.subscription) {
            this.subscription = subscribe(this.messageContext, recordSelected, (message) => this.handleMessage(message), { scope: APPLICATION_SCOPE });
        }
    }
    unsubscribeToMessageChannel() {
        unsubscribe(this.subscription);
        this.subscription = null;
    }
    // Handler for message received by component
    handleMessage(message) {
        const recordData = {
            name: message.recordData.name,
            email: message.recordData.email,
        };
        this.formDataList.push(recordData);
    }
    // Standard lifecycle hooks used to subscribe and unsubsubscribe to the message channel
    connectedCallback() {
        this.subscribeToMessageChannel();
    }
    disconnectedCallback() {
        this.unsubscribeToMessageChannel();
    }
}

ShowFormDetails.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Image 1 :

Salesforce Lightning message

Image 2 :

Salesforce Lightning message

Image 3 :

Salesforce Lightning message