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 fields values. So here need is to display the warning message (not to block update) 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.

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 required field and click on save.

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 lightning component.

So, what is Emp API ?

This lightning empApi module provides the access to methods to subscribe to the streaming channels or listening 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 lightning/empApi module using 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 on 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.

One comment

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