Platform Events in LWC Salesforce

by Rijwan Mohmmed
6 comments
platform-events-in-lwc-salesforce-techdicer

Hello friends, today we will discuss How to use Platform Events in LWC Salesforce. Here we will publish the events in Apex and Subscribe to the LWC component. Platform Events are your ticket to achieving real-time synchronization across Salesforce applications, even in complex scenarios involving multiple systems.

Also, check this: Use Dynamic Styling In LWC Salesforce

platform-events-in-lwc-salesforce-output-techdicer
platform-events-in-lwc-salesforce-output-techdicer

Key Highlights :

  1. With platform events, you can program your apps in a standard way and use an event-based model.
  2. You can also publish the events in the Flow and subscribe to LWC.
  3. Platform event is used to send parameters from one component to another that have no relationship.
  4. Like in my case I fire the event from the Apex class and will subscribe by LWC component.
  5. Instantly update UI components based on data changes without manual refreshes.
  6. Bridge gaps between different Salesforce functionalities and external systems seamlessly.
  7. Platform Events streamline workflows, ensuring actions are triggered precisely when needed.

Process & Code :

Step 1: Define your Platform Event, outlining the data structure you want to communicate. We will create a Platform event and its fields

Setup > Platform Events > click New Platform Event

platform-events-in-lwc-salesforce-platform-event-object-techdicer
platform-eventss-in-lwc-salesforce-platform-event-object-techdicer

platform-events-in-lwc-salesforce-platform-event-fields-techdicer
platform-eventss-in-lwc-salesforce-platform-event-fields-techdicer

Step 2: Emit events when specific conditions are met, using Apex or Process Builder. I will create an Apex class to publish the platform event.

PlatformEventCtrl.cls :

public class PlatformEventCtrl {
    
    public static void publishEvent(){
        Techdicer_Event__e event = new Techdicer_Event__e();
        event.message__c = 'test';
        event.recordId__c = '0016F000041zsTDQAY';
        event.status__c = 'Success';
        EventBus.publish(event);
    }
}

Step 3: Leverage Lightning Web Components to subscribe to these events and take immediate action. Here we will create an LWC component for Subscribe to the event and show data sent by the platform event.

lWCPlatformEvent.HTML :

<template>
    <lightning-card title="Platform Event In LWC Techdicer" icon-name="standard:contact">
        <div class="slds-m-around_medium">
            <p>Status : {status}</p>
            <p>Message : {message}</p>
            <p>Record Id : {recordId}</p>
        </div>
    </lightning-card>
</template>

lWCPlatformEvent.JS :

import { LightningElement, api, track } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class LWCPlatformEvent extends LightningElement {
    @track status;
    @track message;
    @track recordId;

    subscription = {};
    @api channelName = '/event/Techdicer_Event__e';

    connectedCallback() {
        // Register error listener     
        this.registerErrorListener();
        this.handleSubscribe();
    }

    // Handles subscribe button click
    handleSubscribe() {
        // Callback invoked whenever a new event message is received
        const self = this;
        const messageCallback = function (response) {
            console.log('New message received 1: ', JSON.stringify(response));
            console.log('New message received 2: ', response);
            var obj = JSON.parse(JSON.stringify(response));
            console.log(obj.data.payload);
            console.log(obj.data.payload.message__c);
            console.log(self.channelName);
            let objData = obj.data.payload;
            self.message = objData.message__c;
            self.status = objData.Status__c;
            self.recordId = objData.recordId__c;
            self.ShowToast('Techdicer Plaform Event', self.message, 'success', 'dismissable');
        };

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, messageCallback).then(response => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
        });
    }

    //handle Error
    registerErrorListener() {
        onError(error => {
            console.log('Received error from server: ', JSON.stringify(error));
        });
    }

    ShowToast(title, message, variant, mode) {
        const evt = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(evt);
    }
}

lWCPlatformEvent.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__HomePage</target>
	</targets>
	<targetConfigs>
        <targetConfig targets="lightning__HomePage">
            <property name="channelName" type="String" />
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Output :

platform-events-in-lwc-salesforce-output-techdicer
platform-eventss-in-lwc-salesforce-output-techdicer

Reference :

  1. Platform Events In LWC
What’s your Reaction?
+1
8
+1
3
+1
1
+1
0
+1
7
+1
0

You may also like

6 comments

Swapnil Jain March 15, 2023 - 7:24 am

Hi Everyone,
This subscription of platform event in LWC does not for Communities, so if you component is used in Community than any streaming Api won’t work in that, so you need to use CometD library to implement and subscribe the platform event in LWC in community.

Reply
Rick Baker March 23, 2023 - 2:09 pm

Beautifully done. Thanks so much for this. Perfect example. Just what I was look for.

Reply
Pranav May 25, 2023 - 8:29 pm

I have to show modal popup when user mark the opportunity as closed won using opportunity stages path. can we implement this using platform event.

Reply
Rijwan Mohmmed May 26, 2023 - 2:57 am

Yupp We Can

Reply
manoj September 9, 2023 - 1:04 pm

wonder full , i used this functionality to refresh standard compontents . thank u

Reply
Rijwan Mohmmed September 9, 2023 - 3:21 pm

Thanks.

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.