Subscribe Platform Event in Lightning Component

Subscribe Platform Event in Lightning Component

Hello there,

In this post, I am going to share a use case where you can use the platform event.

Use case: There is a custom field on the Contact object called “Contact Data Score”, this field calculates scores (Bad, Warning, Fine) based on the other standard and custom field values. So here need is to display the warning message (not to block updates) to users what fields they can fill or correct to improve the data quality of the contact record. This warning/suggestion message should display after the user clicks on the standard Save button.

Advertisements

Solution :

  • Create a “Platform Event” in your Salesforce org.
  • Create an Apex Trigger on the Contact object.
  • Create a Lightning component.

Apex trigger will check the contact records field values and based on that trigger will publish the event with messages. The lightning component will subscribe to this event and it will listen whenever the event got published. The component will receive the platform event message in the controller method and it will fire a toast event to show the message to end-users.

Platform Event: We can use platform events to connect business processes in Salesforce and external apps through the exchange of real-time event data. Publishers publish event messages that subscribers receive in real-time.

Create a Platform Event.

Go to setup > Search ‘platform event’ and click on Platform event link.

Enter values in the required field and click on save.

Advertisements

Publish Behavior

  • Publish After Commit to have the event message published only after a transaction commits successfully. With this option, a subscriber receives the event message after the data is committed. If the transaction fails, the event message isn’t published.
  • Publish Immediately to have the event message published when the publish call executes, regardless of whether the transaction succeeds. With this option, a subscriber might receive the event message before the data is committed.

Create a text field called message__c

Create a trigger on the Contact object OR if you already have the Trigger written on Contact add the code there.

trigger ContactTrigger on Contact (after insert,after update) {
    if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)){
        List<ContactActivityEvent__e> caeList = new List<ContactActivityEvent__e>();
        String message = 'Please fill below fields to improve the contact data quality score. {fieldNames}';
        for(Contact con: Trigger.new){
            //Check if these fields are not null or empty
            
            if(con.MobilePhone == null ||
               con.Phone == null ||
               con.Birthdate == null ||
               con.Email == null ){
                   
                   //Instantiating platform event
                   ContactActivityEvent__e cae = new ContactActivityEvent__e();
                   //Put the value in the platform event fields
                   String emptyFieldsName = '\n';
                   if(con.MobilePhone == null)
                       emptyFieldsName += '⍟ Mobile Phone'+'\n';
                   if(con.Phone == null)
                       emptyFieldsName += '⍟ Phone'+'\n';
                   if(con.Birthdate == null)
                       emptyFieldsName += '⍟ Birthdate'+'\n';
                   if(con.Email == null)
                       emptyFieldsName += '⍟ Email'+'';
                   
                   String finalMsg = message.replace('{fieldNames}',emptyFieldsName);
                   system.debug('finalMsg => '+ finalMsg);
                   
                   cae.message__c = finalMsg;
                   //add the obj in the list
                   caeList.add(cae);
               }
        }
        //Publish event
        try{
            if(caeList.size()>0)
                EventBus.publish(caeList);
        }catch(Exception e){
            
        }
        
    }
}

We have to use lightning Emp API for listening to platform event messages in the lightning component.

So, what is Emp API?

This lightning empApi module provides the access to methods to subscribe to the streaming channels or listen to the platform events. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events.

In the java-script file of your lightning web component, you can import the methods of the lightning/empApi module using the below syntax.

import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';

Methods :

Method Name Description
subscribe ✤ Subscribes to a given channel and returns a promise that holds a subscription object, which you use to unsubscribe later.
PARAMETER
channel (type = string) >> The channel name to subscribe to.
replayId (type = number) >>Indicates what point in the stream to replay events from. Specify -1 to get new events from the tip of the stream, -2 to replay from the last saved event, or a specific event replay ID to get all saved and new events after that ID.
onMessageCallback (type = function) A callback function that’s invoked for every event received
unsubscribe✤ Unsubscribes from the channel using the given subscription object and returns a promise. The result of this operation is passed into the callback function. The result object holds the successful boolean field which indicates whether the unsubscribe operation was successful.
PARAMETER
subscription (type = object) Subscription object that the subscribe call returned
callback (type = function) A callback function that’s called with a server response for the unsubscribe call.
onError✤ Registers a listener to errors that the server returns.
PARAMETER
callback (type = function) A callback function that’s called when an error response is received from the server for the handshake, connect, subscribe, and unsubscribe meta channels.
setDebugFlag✤ Set to true or false to turn console logging on or off respectively.
PARAMETER
flag (type = boolean) Set to true or false to turn console logging on or off respectively.

Create a lightning component “contactDataQualityNotification”.

<aura:component  implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <lightning:empApi aura:id="empApi" />
    
    <aura:html tag="style">
        .toastMessage.forceActionsText{
        white-space : pre-line !important;
        }
    </aura:html>
</aura:component>

contactDataQualityNotification.js

({
	doInit : function(component, event, helper) {
		var channel = '/event/ContactActivityEvent__e';
        const replayId = -1;
        
        const empApi = component.find("empApi");
        
        //A callback function that's invoked for every event received
        const callback = function (message) {
            var msg = message.data.payload;
            console.log('msg = '+JSON.stringify(msg));
           
            console.log('Message returned : ' +msg.message__c );
            
			//fire toast message
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                "mode": 'sticky',
                "title": "Warning",
                "message": msg.message__c,
                "type" : "warning"
            });
            toastEvent.fire();
        };
        // Subscribe to the channel and save the returned subscription object.
        empApi.subscribe(channel, replayId, callback).then(function(newSubscription) {
            //console.log("Subscribed to channel 1" + channel);
        });
        const errorHandler = function (message) {
            console.error("Received error ", JSON.stringify(message));
        };
        //A callback function that's called when an error response is received from the server for the handshake, connect, subscribe, and unsubscribe meta channels.
        empApi.onError(errorHandler);  
           
	}
})

Add this lightning component to the contact record page.

Let’s check the result: Update any contact record in which one or more field from this list (Email, Phone, Birth-date, Mobile Phone) is empty.

Join 244 other subscribers

Advertisements
Advertisements

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

This Post Has One Comment

  1. Veer

    Thanks A Lot

Leave a Reply