Publish Platform Events in Salesforce?

on

|

views

and

comments

Table of Contents

Introduction

Platform events are a very powerful concept of Salesforce and this becomes very helpful when it comes to integrating multiple systems.

For Example, you wanted to send the order to the OMS system when an order is created within Salesforce. You have various ways to achieve this however platform event will be a good choice to send the required data to OMS.

And now, if the OMS system wants to send the status update the OMS system can send the updates using Platform Event.

What are Platform Events?

Platform events are special kinds of objects that are used to exchange information between the Salesforce and External objects in near-real time.

The identifier for the platform events is that it will always end with __e in Salesforce.

The platform events work with Hub Spoke (Publish-Subscribe) Model where one system(hub) will publish the platform event and the other system(s) will subscribe to the platform event.

The system that is publishing the platform event is known as Hub and the system that is subscribing to the platform event know as Spoke.

Create Platform Events in Salesforce

To create the Platform Event in Salesforce follow the below steps

  • Login to Salesforce
  • Navigate to Setup –> Integration –> Platform Events
  • Click on the “New Platform Event” button
  • Provide the required information and then click on Save.

Below is the complete platform event that I have created for testing purposes.

The platform event is used to send the account information from Salesforce to SAP whenever the account is created inside Salesforce.

Platform Event Publishing Behavior

The publishing behavior of the platform plays an important role while publishing the Platform event. There are 2 kinds of publishing behavior for Platform Events in Salesforce.

  • Publish Immediately
  • Publish After Commit

Publish Immediately

This is self-explanatory as it will publish the platform immediately as soon as you publish it using Apex, flow, or process builder. 

We should be careful while using this behavior for any platform Event.

Let’s talk with an example, we have created the Platform Event for sending the SAP account and we are publishing the Platform Event from Apex Trigger.

After publishing the event there are some further processing happening for the same account record.

As soon as the event is published the subscribers will receive the data no matter if the transaction fails within Salesforce while processing the other part of logic.

Publish After Commit

This type of Platform Event only gets published after all the processing has been completed and the record is committed into Salesforce.

Now, if we take the same example above, we have published the event and then later point in the code there is some error and the transaction gets rolled back in this case the Platform Event will not get published.

Publish Platform Event from Salesforce

We have different ways to publish the platform event from Salesforce.

  • Apex Trigger(s)/Apex Class(es)
  • Lightning Flows
  • Lightning Web Component/Lightning Aura Component

Publish Platform Event using Apex Class

It is very simple to publish the event because platform events are just a special type of object. We need to prepare the events similar to a custom or standard object.

For Example, our test platform event SAPAccountEvent__e that have only two fields.

So, we will prepare the platform event like below

				
					SAPAccountEvent__e  sapEvent = new SAPAccountEvent__e(
    	AccountId__c = '0014x0000061xe3AAA',
        AccountName__c = 'United Oil & Gas, Singapore'
    );
    // Publish the Event using EventBus class
    EventBus.publish(sapEvent);
				
			

If you have noticed that we are preparing the instance of the Platform Event using the same way we do for any Custom or Standard Object.

To publish the event we need to use EventBus class that has a method “publish” that accepts single platform events or multiple platform events.

For more information visit this link – https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_eventbus.htm#apex_System_eventbus_publish

Publishing Event using Lighting Flows

To publish the Platform Event from the Salesforce Lightning Flows we can utilize the Create Records data element provided by Salesforce.

We can publish the platform event from any kind of Lightning Flow.

Below is the sample screenshot for the same.

Publish the Platform Event using Lightning Web Component

To publish the event from the Lightning Web Component, we need to call the Apex Class and that class will use the same concept as we discussed above to publish the event.

Subscribe the Platform Event in Salesforce

Like publishing the platform event we have multiple ways to subscribe to the platform event in Salesforce.

  • Apex Trigger
  • Lightning Flows
  • Salesforce Workbench
  • Lightning Web Component

Subscribe to Platform Event using Apex Trigger

Apex Trigger is the easiest way to subscribe to the platform event in Salesforce because we can write the apex trigger like the same way we do write the trigger for any other standard or custom object.

				
					trigger SAPAccountEventTrigger on SAPAccountEvent__e (after insert) {

}
				
			

Subscribe to Platform Event using Flow Builder

As we have seen we can publish the Platform Event using Flow Builder. 

Let’s follow the steps to subscribe to the events using Flows.

  • Login to Salesforce
  • Navigate to Setup –> Flows –> New Flow
  • Select Platform Event – Triggered Flow

Select your platform event and then click on Done.

Once you have selected your channel do the manipulation on the data like creating the records for a custom object or Send and Email or Update the record.

Subscribe Platform Event using Workbench

Workbench is a web-based platform that is managed by Salesforce. We can do so many things but we will focus on how we can subscribe to the Platform Event using Workbench.

Log in to Workbench using  https://workbench.developerforce.com/login.php

Navigate to Queries –> Steaming Push Topics –> Select Generic Subscriptions

Provide the event name in the given format

/event/<PlatformEventName__e>

Subscribe to Platform Event using Lightning Web Component

As we all know Lighting Web Components is the hot tech stack these days. And LWC is also one of the tools that we can use to subscribe to the Platform Event.

To subscribe to the Platform Event in LWC we need to use empApi. The very first step after creating the LWC is to import the empApi methods in JavaScript Class

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

The empApi has 2 main methods subscribe & unsubscribe. subscribe is used to subscribe to the channel and unsubscribe is used to unsubscribe from the channel.

Take a look at below code for your reference

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

export default class EmpApiLWC extends LightningElement {

    channelName = '/event/SAPAccount__e';

    subscription = {};

    handleChannelName(event) {
        this.channelName = event.target.value;
    }

    connectedCallback() {
        this.registerErrorListener();
    }

    disconnectedCallback() {
        this.handleUnsubscribe();
    }


    handleSubscribe() {
        subscribe(this.channelName, -1, this.subscribedata.bind(this)).then((response) => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: ', JSON.stringify(response.channel));
            this.subscription = response;
        });
    }

    subscribedata(response) {
        console.log(`Response from Event ${response}`);
    }

    handleUnsubscribe() {
        unsubscribe(this.subscription, (response) => {
            console.log('unsubscribe() response: ', JSON.stringify(response));
        });
    }

    registerErrorListener() {
        onError((error) => {
            console.log('Received error from server: ', JSON.stringify(error));
        });
    }
}
				
			
				
					<template>
    <lightning-card  variant="Narrow" title="Platform Event" icon-name="standard:account">
        <div class="slds-m-around_small">
            <p>
                <lightning-button variant="brand" label="Subscribe" title="Subscribe" onclick={handleSubscribe}></lightning-button>
            </p>
            <p>
                {responseString}
            </p>
        </div>
    </lightning-card>
</template>
				
			

Platform Event Limitation

As we all know that Salesforce runs on a multi-tenant platform so it has some limitations related to Platform Events as well.

Here are some common platform event allocations/limitations

  • Developer Edition – 5
  • Enterprise Licence – 50
  • Performance & Unlimited Edition – 100
  • Professional Edition (with API Add-On) – 5
  • Developer Edition – 20
  • Enterprise Licence – 1,000
  • Performance & Unlimited Edition – 2,000
  • Professional Edition (with API Add-On) – 20
  • Developer Edition – 4,000
  • Enterprise Licence – 4,000
  • Performance & Unlimited Edition – 4,000
  • Professional Edition (with API Add-On) – 4

For more information visit – Salesforce Document

Related Articles

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Read More »

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been

Read More »
Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential