Platform Events in LWC Salesforce

by Rijwan Mohmmed
0 comment
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.

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 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 apex class and will subscribe by LWC component.

Process & Code :

Step 1: First of all 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-events-in-lwc-salesforce-platform-event-object-techdicer

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

Step 2: In this step, 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: Here we will create an LWC component for Subscribe the event and show data which send 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-events-in-lwc-salesforce-output-techdicer

Reference :

  1. Platform Events In LWC

You may also like

Leave a Comment