Tag: Platform Events

Publishing Platform Events

The Salesforce enterprise messaging platform offers the benefits of event-driven software architectures. Platform events are the event messages (or notifications) that your apps send and receive to take further action. Platform events simplify the process of communicating changes and responding to them without writing complex logic. Publishers and subscribers communicate with each other through events. One or more subscribers can listen to the same event and carry out actions. Here we will see how many ways you can able to publish the platform events in Salesforce. After a platform event has been defined in your Salesforce org, publish event messages from a Salesforce app using processes, flows, or Apex or an external app using Salesforce APIs.Here is the simple platform event object we will be using in the examples here

Here are the different ways you can able to publish the platform events in Salesforce

Option 1: Using Process Builder  

You can able to publish the platform events using process builder. To publish event messages, add a Create a Record action to the appropriate process. Where you’d usually pick an object to create, select the platform event. Here is the simple process builder that will publish the platform event when an order is created

This process builder will publish the platform event whenever the order record is created.

Option 2: Using flow 

Another great usage of the flow is you can able to publish the platform events using the flows. Use flows to publish event messages from a Salesforce app as part of some user interaction, an automated process, Apex, or workflow action. To publish event messages, add a Record Create or a Fast Create element to the appropriate flow. Where you’d usually pick an object to create, select the platform event. Here is the simple flow that we will be using it create a platform event on click on the button from the order record. Here is the Fast lookup screen that will fetch the order from the database.

Here is the record create screen that will be inserting the data into the platform event.

Final Flow looks like below

Now create a quick action from the flow and add it to the order page layout. once you click on the quick action then it will publish into the platform events.

Option 3: Using Apex

You can able to publish the platform event using apex. To publish event messages, call the EventBus.publish method. Here is the sample apex trigger that will create platform events.

trigger Ordertrigger on Order (after insert) {
    List<Order_Fulfillment__e> listOfOF = new List<Order_Fulfillment__e>();
    for(Order o :Trigger.new){
        Order_Fulfillment__e ofD = new Order_Fulfillment__e() ;  
        ofD.Is_Primary__c = true ; 
        ofD.Order_Date__c = System.today() ;
        ofD.Order_Details__c = o.Description ; 
        ofD.Order_Id__c =o.Id ; 
        ofD.Sales_Price__c = o.TotalAmount ; 
        ofD.Status__c = o.Status ; 
        ofD.Type__c = o.Type;
    List<Database.SaveResult> results = EventBus.publish(listOfOF);
    for (Database.SaveResult sr : results) {
        if (sr.isSuccess()) {
            System.debug('Successfully published event.');
        } else {
            for(Database.Error err : sr.getErrors()) {
                System.debug('Error returned: ' +
                             err.getStatusCode() +
                             ' - ' +

Option 4: Using External Apps 

You can able to publish the platform events by using third-party apps with API support. For example, you can able to publish the platform events using SoapUI. Please refer to this link 

Option 5: Using Salesforce APIs

External apps use an API to publish platform event messages. Publish events by creating records of your event in the same way that you insert sObjects. You can use any Salesforce API to create platform events, such as SOAP API, REST API, or Bulk API. When publishing an event message, the result that the API returns contains information about whether the operation was successful and the errors encountered. If the success field is true, the event was published for a standard-volume event. For a high-volume event, the publish request is queued in Salesforce and the event message might not be published immediately. If the success field
is false, the event publish operation resulted in errors, which are returned in the errors field. The returned result also contains the Id system field. The Id field value is not included in the event message delivered to subscribers. It is not used to identify an event message, and is not always unique. Subscribers can use the ReplayId system field, which is included in the delivered message, to identify the position of the event in the stream. To publish a platform event message using REST API, send a POST request to the following endpoint.


You can able to send the post request as shown below from workbench as shown below.



Platform Events Subscribe using Lightning Component

Platform events are part of Salesforce’s enterprise messaging platform. The platform provides an event-driven messaging architecture to enable apps to communicate inside and outside of Salesforce. Here let us discuss how to subscribe to the platform events in the lightning component using lightning: empApi. The lightning:empApi component provides access to methods for subscribing to a streaming channel and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events. The lightning:empApi component uses a shared CometD connection.we will be subscribing the platform event object as shown below.
Here is the simple lightning component that will subscribe to the platform events and listen for notifications.
<aura:component implements="flexipage:availableForAllPageTypes ,force:appHostable" access="global" >
    <lightning:empApi aura:id="empApi" />
    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
    <aura:attribute name="subscription" type="Object" />
    <aura:attribute name="results" type="Object" />
    <lightning:input aura:id="channel" label="channel" name="channel" type="text" value="/event/Order_Fulfillment__e"/>
    <lightning:button label="Subscribe" onclick="{! c.subscribe }" />
    <lightning:button label="Unsubscribe" onclick="{! c.unsubscribe }" disabled="{!empty(v.subscription)}"/>
    // Sets an empApi error handler on component initialization
    onInit : function(component, event, helper) {
        // Get the empApi component
        const empApi = component.find('empApi');
        //  below line to enable debug logging (optional)
    // Invokes the subscribe method on the empApi component
    subscribe : function(component, event, helper) {
        // Get the empApi component
        const empApi = component.find('empApi');
        // Get the channel from the input box
        const channel = component.find('channel').get('v.value');
        // Replay option to get new events
        const replayId = -1;

        // Subscribe to an event
        empApi.subscribe(channel, replayId, $A.getCallback(eventReceived => {
            // Process event (this is called each time we receive an event)
			component.set('v.results', JSON.stringify(eventReceived.data.payload));
            console.log('Received event 1 ', eventReceived.data);

            console.log('Received event2  ', eventReceived.data.payload);
        .then(subscription => {
            // Confirm that we have subscribed to the event channel.
            // We haven't received an event yet.
            console.log('Subscribed to channel ', subscription.channel);
            // Save subscription to unsubscribe later
            component.set('v.subscription', subscription);

    // Invokes the unsubscribe method on the empApi component
    unsubscribe : function(component, event, helper) {
        // Get the empApi component
        const empApi = component.find('empApi');
        // Get the subscription that we saved when subscribing
        const subscription = component.get('v.subscription');

        // Unsubscribe from event
        empApi.unsubscribe(subscription, $A.getCallback(unsubscribed => {
          // Confirm that we have unsubscribed from the event channel
          console.log('Unsubscribed from channel '+ unsubscribed.subscription);
          component.set('v.subscription', null);


once a platform event is published, you can able to the response from the subscribed lightning component as shown below

Publishing Platform Events using SoapUI

Here lets us discuss how to publish the Salesforce platform events using the SoapUI.Use platform events to deliver secure and scalable custom notifications within Salesforce or from external sources. Platform events are part of Salesforce’s enterprise messaging platform. The platform provides an event-driven messaging architecture to enable apps to communicate inside and outside of Salesforce. Here is the simple platform event object 

1. Get  Enterprise WSDL

Here we’re using the enterprise WSDL to explore SOAP API. To get the WSDL, from Setup, enter API in the Quick Find box, then select API. On the API WSDL page, click Generate Enterprise WSDL.save the WSDL file to the local repository.

2. Create a Project in SoapUI 

File menu, select New SOAP Project and create a new project as shown below.

3. Get SessionId

In SoapUI, scroll down to the login operation. Expand it, and then double-click Request 1. A sample SOAP login request appears.

here is the soapUI request you need to send it as part of the request. after successfully login request, you will get the session id and instance URL.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">

4. Create a Platform Event 

now use create operation to create a platform event as shown below

Here is the sample request that will be used to create a salesforce platform event. once you execute the request you will return the response with the platform event id

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
         <!--Zero or more repetitions:-->
         <urn:sObjects xsi:type="Shipments__e" 
			<urn:fieldsToNull xsi:nil="true"/>
			<urn:Id xsi:nil="true"/>

5.Subscribe to platform events 

Here is the simple trigger that will subscribe to platform events and create a simple task to the user.

trigger Subscribe on Shipments__e (after insert) {
    List<Task> tasks = new List<Task>();
    for (Shipments__e event : Trigger.New) {
        if (event.Delivered__c == true) {
            Task t = new Task();
            t.Priority = 'Medium';
            t.ActivityDate= System.today()+10;
            t.Subject = 'Follow up on shipped order ' + event.Shipment_Number__c;
            t.OwnerId = UserInfo.getUserId();
    if (tasks.size() > 0) {
        insert tasks;


Fire Platform Events from Batch Apex Classes


With winter 19 release you can able to fire the platform events from the batch apex.Batch Apex classes can opt in to fire platform events when encountering an error or exception. Clients listening on an event can obtain actionable information, such as how often the event failed and which records were in scope at the time of failure. Events are also fired for Salesforce Platform internal errors and other uncatchable Apex exceptions such as LimitExceptions, which are caused by reaching governor limits. An event record provides more granular error tracking than the Apex Jobs UI. It includes the record IDs being processed, exception type, exception message, and stack trace. You can also incorporate custom handling and retry logic for failures. You can invoke custom Apex logic from any trigger on this type of event, so Apex developers can build functionality like custom logging or automated retry handling. To fire a platform event, a batch Apex class declaration must implement the Database.RaisesPlatformEvents interface.

Step 1:  Create a Platform event

Here is the simple platform event object created for this example 

Step 2: Subscribe to platform event

I just created a simple trigger to subscribe for the platform events. During this beta release, Process Builder and flows do not support subscribing to these events.

// Trigger for listening to Cloud_News events.
trigger CloudNewsTrigger on Cloud_News__e (after insert) {    
    // List to hold all cases to be created.
    List<Case> cases = new List<Case>();
    // Iterate through each notification.
    for (Cloud_News__e event : Trigger.New) {
        if (event.Urgent__c == true) {
            // Create Case to dispatch new team.
            Case cs = new Case();
            cs.Priority = 'High';
            cs.Subject = 'News team dispatch to ' +event.Location__c;
    // Insert all cases corresponding to events received.
    insert cases;

Step 3: Raise Platform events

now you can raise the platform event from the batch apex.here is the simple batch apex that will raise the platform evens. After raising platform events all the subscribed channel will be receiving the events.

global with sharing class PlatformEventRaise implements Database.Batchable<SObject>, Database.RaisesPlatformEvents{
    // class implementation
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator('Select Id ,Name,Rating,Industry, BillingAddress,BillingStreet,BillingCity, BillingCountry, BillingPostalCode,BillingState,Phone from Account  where BillingStreet!=NULL');
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        List<Account> accs =(List<Account>) scope ; 
        List<Cloud_News__e> cnewList = new List<Cloud_News__e>();
        for(Account a : accs){
            // Create an instance of the event and store it in the newsEvent variable
            Cloud_News__e newsEvent = new Cloud_News__e(
            cnewList.add(newsEvent) ;
    global void finish(Database.BatchableContext BC){

Go and execute batch apex

After raising the platform events, the subscribed trigger will create a case as shown below


Event Error Handling

The BatchApexErrorEvent object represents a platform event associated with a batch Apex class. This example creates a trigger to determine which accounts failed in the batch transaction. Custom field Dirty__c indicates that the account was one of a failing batch and ExceptionType__c indicates the exception that was encountered. JobScope and ExceptionType are fields in the BatchApexErrorEvent object.

trigger MarkDirtyIfFail on BatchApexErrorEvent (after insert) {
    Set<Id> asyncApexJobIds = new Set<Id>();
    for(BatchApexErrorEvent evt:Trigger.new){
    Map<Id,AsyncApexJob> jobs = new Map<Id,AsyncApexJob>(
        [SELECT id, ApexClass.Name FROM AsyncApexJob WHERE Id IN :asyncApexJobIds]
    List<Account> records = new List<Account>();
    for(BatchApexErrorEvent evt:Trigger.new){
        //only handle events for the job(s) we care about
        if(jobs.get(evt.AsyncApexJobId).ApexClass.Name == 'PlatformEventRaise'){
            for (String item : evt.JobScope.split(',')) {
                Account a = new Account(
                    Id = (Id)item,
                    ExceptionType__c = evt.ExceptionType,
                    Dirty__c = true
    update records;


Platform Events in Salesforce


In this blog post, I am going to explain about platform events a new feature generally available from Summer ’17 release as part of the “Enterprise Message Platform” which provide event driven architecture.

Let’s talk about Event Driven Architecture 

Salesforce event-driven architecture is consists of event producers, event consumers, and channels.  Platform events simplify the process of communicating changes and responding to events. Publishers and subscribers communicate with each other through events. One or more subscribers can listen to the same event and carry out actions .with an Event-driven architecture each service publishes an event whenever it updates or creates a data. Other services can subscribe to events.It enables an application to maintain data consistency across multiple services without using distributed transactions.  Let us take an example of order management. When the Order management app creates an Order in a pending state and publishes an OrderCreated event.The Customer Service receives the event and attempts to process an Order. It then publishes an OrderUpdate event.Then OrderUpdate Service receives the event from the changes the state of the order to either approved or canceled or fulfilled.The following  diagram show the event driven architect



A change in state that is meaningful in a business process. For example, a placement o of an order is a meaningful event because the order fulfillment center requires notification to process the order.
Event Notifier 
A message that contains data about the event. Also known as an event notification.
Event producer
The publisher of an event message over a channel.
A conduit in which an event producer transmits a message. Event consumers subscribe to the channel to receive messages.
Event consumer
A subscriber to a channel that receives messages from the channel. A change in state that is meaningful in a business process.

Looks like Streaming API, But Really not 

But when you overlook at Platform events it makes similar to Streaming API and most of the futures including the replayID and durability but below makes the difference between with streaming API.

  • Platform  events are special kinds of entity similar to custom object custom object
  • You can publish and consume platform events by using Apex or a REST API or SOAP API. Platform events integrate with the Salesforce platform through Apex triggers. Triggers are the event consumers on the Salesforce platform that listen to event messages.Unlike custom objects, you can’t update or delete event records. You also can’t view event records in the Salesforce user interface, and platform events don’t have page layouts. When you delete a platform event definition, it’s permanently deleted.
  • Platform events may be published using declarative tools (Process Builder)
  • platform events can also be subscribed to using APEX  or decoratively process builder  and flows

Another major,off-course really impressive one is you can publish changes from apex trigger and you can consume from apex trigger trigger

Publishing and subscribing Platform events 

Publishing and subscribing the platform event are more flexible. You can publish event messages from a Force.com app or an external app using Apex or Salesforce APIs and you can subscribe from the Salesforce or external apps or use long polling with cometD as well.

Let’s take an Example:- 

Now I am going to explain step by step to set up, publish and consume events. What we are going to do it Employee Onboarding Process. Now Once an external app publishes the events, we are going to create an account and when Salesforce publish onboarding events another system is going to receive the platform events.

1: – Define a Platform event

You can define platform event similar like custom object, go to setup –> develope –> Platform events –> create new platform events as shown below.


By seeing it looks like custom objects but here are the few major considerations.

  • Platform event is appended the __e suffix for API name of the event.
  • you can’t query Platform events through SOQL or SOSL.
  •  you can’t use Platform in reports, list views, and search.
  •  published platform events can’t be rolled back.
  • e methods aren’t supported with platform events.
  • All platform event fields are read-only by default
  • Platform events don’t have an associated tab
  • Only after insert Triggers Are Supported
  • You can access platform events both through API and declaratively
  • You can control platform events though Profiles and permissions

2: – Publishing Platform Events

You can publish events using an Apex method or with declarative tools, such as Process Builder or the Cloud Flow Designer or you can publish events using Salesforce API. we are going to seeing all the ways how to publish the platform events.

Publish Using Apex

you can publish platform events by using apex trigger or execute anonymously and batch Apex etc.But here I am going to publish by using Apex triggers. A trigger processes platform event notifications sequentially in the order they’re received and trigger runs in its own process asynchronously and isn’t part of the transaction that published the event.

trigger PlatformEventPublish on Account (after insert , after update ) {
    If(trigger.isAfter && trigger.isUpdate){
        List<Employee_On_boarding__e> publishEvents = new List<Employee_On_boarding__e>();
        for(Account a : Trigger.new){
            Employee_On_boarding__e eve = new Employee_On_boarding__e();
            eve.Name__c = a.Name ; 
            eve.Phone__c = a.Phone ; 
            eve.Salary__c = a.AnnualRevenue ; 


 Now if you can see, Salesforce has a special class to publish the platform events EventBus which is having methods publish method. once the event is published you can consume the events from the channel

Publish Using Process Builder 

You can publish platform events using the declarative tools like process builders and flows. Here is the image shows the platform events insert by using process builder.


Publish Events by Using API


Now I am going to see another way of publishing events from API. I am going to use the workbench to publish the events.

3: – Subscribe for Platform events from the channel

You can now subscribe to the platform events from the Platform events object trigger which is created in step 1. Here is the sample trigger show how you can handle the subscribed events. Here simply I am creating new accounts from the platform even but you can implement your own business logic to update the data .

trigger OnBoaringTrigger on Employee_On_boarding__e (after insert) {
    List<Account> acc = new List<Account>();
    for(Employee_On_boarding__e oBording :trigger.new){
        acc.add(new Account(Name =oBording.Name__c , Phone =oBording.Phone__c , AnnualRevenue = oBording.Salary__c));
    if(acc.size() >0){
        insert acc ;


Here is the simple visual force page that consumes the platform events which you published. This page is built on cometD.
you can consume the platform events by using this  URI /event/Employee_On_boarding__e and the Complete code is here below.

<apex:page standardStylesheets="false" showHeader="false" sidebar="false">
    <div id="content">
    <apex:includeScript value="{!$Resource.cometd}"/>
    <apex:includeScript value="{!$Resource.jquery}"/>
    <apex:includeScript value="{!$Resource.json2}"/>
    <apex:includeScript value="{!$Resource.jquery_cometd}"/>
    <script type="text/javascript">
        $(document).ready(function() {
                url: window.location.protocol+'//'+window.location.hostname+ (null != window.location.port ? (':'+window.location.port) : '') +'/cometd/40.0/',
                requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
            $.cometd.addListener('/meta/handshake', function(message) {
                $.cometd.subscribe('/event/Employee_On_boarding__e', function(message) {
                    var div = document.getElementById('content');
                    div.innerHTML = div.innerHTML + '<p>Notification </p><br/>' +
                        'Streaming Message ' + JSON.stringify(message) + '</p><br>';

Key points

1 . Platform events are executed under ” Automated Process entity.” So you have set Automated Process in debug logs
2. You can control the Platform events on Profile and permission sets
3.You can see all the platform events that are subscribed under Platform events objects.
4. Platform events have lifecycles state like Running, Ideal, Suspended,, Error, Expired
5.Platform events are having retry mechanism.

if (EventBus.TriggerContext.currentContext().retries < 4) {
// Condition isn't met, so try again later.
throw new EventBus.RetryableException(
'Condition is not met, so retrying the trigger again.');
} else {
// Trigger was retried enough times so give up and
// resort to alternative action.
// For example, send email to user.