Platform Event

Platform Event

Introduction to Platform Events in Salesforce :

  • Consider this, a platform event is just like another custom object but this would only be referred by external systems to communicate with Salesforce. 
  • To put this in a scenario when a certain system posts data on a Salesforce endpoint then that data should be fetched and the data in Salesforce should be updated. 
  • Of course, you can use too many lines of code to continuously fetch and retrieve the data from the endpoint or just wait for data to be posted based on which an event shall be triggered and the next processes shall follow. 
  • Now, this is where platform events come into the picture, instead of writing lines and lines of codes and continuously requesting and checking if the data is posted we can just have a platform event trigger notify us and then have your logic do the rest of the heavy lifting.

What are Platform Events in Salesforce?

  • Platform Event is based on Event-Driven Architecture which enables apps to communicate inside and outside of Salesforce. 
  • Platform events are based on the publish/subscribe model and work directly with a message bus which handles the queue of incoming events and processes listening for them. 
  • This is built in real time integration patterns in the Salesforce Platform which helps to reduce point-to-point integration.

Here Are The Following Points We Should Remember :

  • Event: An adjustment in the expression that is important in a business procedure. 
  • Event Message/Notification: A message that contains information about the Event. 
  • Event Maker: The distributer of an occasion message over a channel. 
  • Channel: A conductor where an occasion maker sends a message. Event shoppers buy into the channel to get messages. Likewise alluded to as Event transport in Salesforce. 
  • Event Consumer: A supporter of a channel that gets messages from the channel.

Publishing and subscribing Platform events :

  • Publishing and subscribing to 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.

Define Platform Event :

Define platform events similar like a custom object, go to setup –> develope –> Platform events –> create new platform events as shown below.

Publish Platform events

Publish Using Apex :

  • A trigger processes platform event notification 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. 
  • 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.

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 ;

            publishEvents.add(eve);            

        }

        if(publishEvents.size()>0){

            EventBus.publish(publishEvents);

        }

    }

}

Publish Using Process Builder :

Publish Events by Flow :

  • Run/Debug Flow:1(platform Event producer) and you will send post in chatter.

Result:

Subscribe for Platform events :

  • We can subscribe to the platform events from the Platform events object trigger which is created. 
  • Here is the sample trigger show how you can handle the subscribed events. create new accounts from the platform event but you can implement your own business logic to update the data.

trigger OnBoardingTrigger 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 ;

    }

}

  • 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”> 

    </div>

    <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”>

    (function($){

        $(document).ready(function() {

            $.cometd.configure({

                url: window.location.protocol+’//’+window.location.hostname+ (null != window.location.port ? (‘:’+window.location.port) : ”) +’/cometd/40.0/’,

                requestHeaders: { Authorization: ‘OAuth {!$Api.Session_ID}’}

            });

            $.cometd.handshake();

            $.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>’;

                });

            })

        });

    })(jQuery)

    </script>

</apex:page>

    

Advantages of Salesforce Platform Events :

  • Clients can run organizations quicker on an event-driven architecture.
  • Make an entire 360-degree client experience – continuous reconciliation with any business cycle.
  • Event-driven work processes to enlarge information.
  • Can catch and follow up on a great many streaming events.