Lightning

LWC: How to create Lightning Message Channel?

You need Lightning Message Channel for Lightning Web Component Message Service to work. Below are the steps with which you can create Lightning Message Channel.


Step 1:  Create a folder with name: “messageChannels”

Step 2: Create a file with any name followed by an extension “.messageChannel-meta.xml”

Ex: Sample_Channel_File.messageChannel-meta.xml

Step 3: Below is a simple code

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

    <lightningMessageFields>
        <fieldName>a_Variable1</fieldName>
        <description>Variable 1 Description - optional</description>
    </lightningMessageFields>

    <lightningMessageFields>
        <fieldName>a_Variable2</fieldName>
        <description>Variable 2 Description - optional</description>
    </lightningMessageFields>

</LightningMessageChannel>

Here, you can add or remove LightningMessageFields as required.

Step 4: Add LightningMessageChannel as type in Package.xml file.

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

Step 5: Deploy the message channel xml file.

  • Right Click
  • SFDX: Deploy This Source to Org

Note:

To use the channel in visualforce page or Aura component or Web component. You need to use the file name of channel followed by __c

Ex: in above example file name is Sample_Channel_File, so to use this channel you need to mention it as Sample_Channel_File__c

In LWC it will be

import a_LMS_Channel from "@salesforce/messageChannel/Sample_Channel_File__c";

In Aura it will be

<lightning:messageChannel type="Sample_Channel_File__c" aura:id="Sample_Channel_File__ID" onMessage="{!c.a_Method_To_Execute}"/>

In VisualForce page script tag

const GINFO = "{!$MessageChannel.Sample_Channel_File__c}"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s