Lightning Message Channel in LWC

Share This Post

The Lightning Message Channel (LMC) in Salesforce Lightning Web Components (LWC) is a powerful feature that facilitates communication between Lightning Web Components (LWC) and Aura components. It provides a way for components to send and receive messages without being directly related to the component hierarchy, making it an essential tool for building dynamic and responsive applications.

What is a Lightning Message Channel?

A Lightning Message Channel is an event-based communication mechanism that allows Lightning Web Components and Aura components to communicate with each other by publishing and subscribing to messages. This decoupled approach enhances flexibility and scalability in Salesforce applications.

Key Features:

  1. Decoupled Communication: Components don’t need to be directly related in the component hierarchy.
  2. Event-Based: Uses an event-based model to publish and subscribe to messages.
  3. Cross-Component Communication: Enables communication across different components, whether part of the same page or other pages.

Creating a Lightning Message Channel

To use the Lightning Message Channel, follow these steps:

Create a Message Channel

    <?xml version="1.0" encoding="UTF-8"?>
    
    <LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    
        <masterLabel>ContactMessageChannel</masterLabel>
    
        <isExposed>true</isExposed>
    
        <description>Message channel for sending Contact details</description>
    
    </LightningMessageChannel>

    Publish a Message

      To publish a message, you need to use the LightningElement and publish method from lightning/messageService.

      Here’s an example of a component that publishes a message:

      <template>
          <lightning-combobox
              name="contact"
              label="Select Contact"
              value={selectedContactId}
              placeholder="Select a Contact"
              options={contactOptions}
              onchange={handleContactChange}>
          </lightning-combobox>
          <lightning-button label="Send Contact Details" onclick={publishContactDetails}></lightning-button>
      </template>
      import { LightningElement, wire, track } from 'lwc';
      import { publish, MessageContext } from 'lightning/messageService';
      import CONTACT_MESSAGE_CHANNEL from '@salesforce/messageChannel/ContactMessageChannel__c';
      import getContacts from '@salesforce/apex/ContactController.getContacts';
      
      export default class ContactPublisher extends LightningElement {
          @track contactOptions = [];
          @track selectedContactId = '';
      
          @wire(MessageContext)
          messageContext;
      
          @wire(getContacts)
          contacts(result) {
              if (result.data) {
                  console.log('Contacts data:', result.data);
                  this.contactOptions = result.data.map(contact => ({
                      label: contact.Name,
                      value: contact.Id
                  }));
              } else if (result.error) {
                  console.error('Error loading contacts:', result.error);
              }
          }
      
          handleContactChange(event) {
              this.selectedContactId = event.detail.value;
          }
      
          publishContactDetails() {
              const message = {
                  contactId: this.selectedContactId
              };
      
              publish(this.messageContext, CONTACT_MESSAGE_CHANNEL, message);
          }
      }

      Subscribe to a Message

      To receive messages, use the subscribe method from lightning/messageService.

      Here’s an example of a component that subscribes to the message:

      <template>
          <template if:true={contact}>
              <lightning-card title="Contact Details">
                  <p><strong>Name:</strong> {contact.Name}</p>
                  <p><strong>Email:</strong> {contact.Email}</p>
                  <p><strong>Phone:</strong> {contact.Phone}</p>
              </lightning-card>
              <template if:true={account}>
                  <lightning-card title="Account Details">
                      <p><strong>Account Name:</strong> {account.Name}</p>
                      <p><strong>Account Phone:</strong> {account.Phone}</p>
                  </lightning-card>
              </template>
          </template>
          <template if:false={contact}>
              <p>No contact details available.</p>
          </template>
      </template>
      import { LightningElement, wire, track } from 'lwc';
      import { subscribe, MessageContext } from 'lightning/messageService';
      import CONTACT_MESSAGE_CHANNEL from '@salesforce/messageChannel/ContactMessageChannel__c';
      import getContactById from '@salesforce/apex/ContactController.getContactById';
      import getAccountById from '@salesforce/apex/AccountController.getAccountById';
      
      export default class ContactSubscriber extends LightningElement {
          @track contact;
          @track account;
      
          @wire(MessageContext)
          messageContext;
      
          connectedCallback() {
              this.subscribeToMessageChannel();
          }
      
          subscribeToMessageChannel() {
              this.subscription = subscribe(
                  this.messageContext,
                  CONTACT_MESSAGE_CHANNEL,
                  (message) => this.handleMessage(message)
              );
          }
      
          handleMessage(message) {
              const contactId = message.contactId;
      
              getContactById({ contactId })
                  .then(contactData => {
                      this.contact = contactData;
      
                      if (contactData.AccountId) {
                          return getAccountById({ accountId: contactData.AccountId });
                      }
                      return null;
                  })
                  .then(accountData => {
                      this.account = accountData;
                  })
                  .catch(error => {
                      console.error('Error fetching contact or account details:', error);
                  });
          }
      }

      Apex Class

      /**
      * @File Name : ContactController.cls
      * @Description :
      * @Author :
      * @Last Modified By :
      * @Last Modified On : August 27, 2024
      * @Modification Log :
      *==============================================================================
      * Ver | Date | Author | Modification
      *==============================================================================
      * 1.0 | August 27, 2024 |   | Initial Version
      **/
      
      public with sharing class ContactController {
          @AuraEnabled(cacheable=true)
          public static List<Contact> getContacts() {
              return [SELECT Id, Name FROM Contact];
          }
      
          @AuraEnabled(cacheable=true)
          public static Contact getContactById(Id contactId) {
              return [SELECT Id, Name, Email, Phone, AccountId FROM Contact WHERE Id = :contactId LIMIT 1];
          }
      }
      /**
      * @File Name : AccountController.cls
      * @Description :
      * @Author :
      * @Last Modified By :
      * @Last Modified On : August 27, 2024
      * @Modification Log :
      *==============================================================================
      * Ver | Date | Author | Modification
      *==============================================================================
      * 1.0 | August 27, 2024 |   | Initial Version
      **/
      
      public with sharing class AccountController {
          @AuraEnabled(cacheable=true)
          public static Account getAccountById(Id accountId) {
              return [SELECT Id, Name, Phone FROM Account WHERE Id = :accountId LIMIT 1];
          }
      }

      Conclusion

      The Lightning Message Channel provides a robust mechanism for communication between Salesforce components, enhancing the flexibility and responsiveness of your Lightning applications. By following the steps outlined above, you can easily implement a message channel in your LWC components to streamline communication and build more dynamic user experiences.

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      Subscribe To Our Newsletter

      Get updates and learn from the best

      More To Explore

      Validation Rule Practice Question – Part 2

      Validation rules are an essential feature in Salesforce that ensures data quality by enforcing specific conditions when users input data into fields. Whether you’re a