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
Key Highlights :
- With platform events, you can program your apps in a standard way and use an event-based model.
- You can also publish the events in the Flow and subscribe to LWC.
- Platform event is used to send parameters from one component to another that have no relationship.
- Like in my case I fire the event from the Apex class and will subscribe by LWC component.
- Instantly update UI components based on data changes without manual refreshes.
- Bridge gaps between different Salesforce functionalities and external systems seamlessly.
- 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
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>
6 comments
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.
Beautifully done. Thanks so much for this. Perfect example. Just what I was look for.
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.
Yupp We Can
wonder full , i used this functionality to refresh standard compontents . thank u
Thanks.