Sharing is caring!
You must have encountered with the term Platform Events often.
Platform events are part of the Salesforce messaging platform. They are based on Event-Driven Architecture, which allows the apps to communicate inside and outside of Salesforce.
These events are based on the publish and subscribe model, which works directly with a message bus to handle the queue of incoming events and the processes that listen to them.
They are built using real-time integration patterns, which helps to reduce point-to-point integration. They help to accelerate development and are faster than point-to-point integration. These are modular components that are reusable across various integrations.
Various top-notch Salesforce integration companies such as Cloud Analogy – a Salesforce Gold Consulting Partner, provide the service for the real-time integration.
This blog will provide Insights into the terminologies of platform events, an understanding of platform events, and the steps to create platform events and ways to publish and subscribe to platform events in Salesforce.
Platform Event Terminology
- Event: It is a meaningful change in state for a business process.
- Event message: A message that contains data related to the event.
- Event producer: It is the publisher of an event message over a channel.
- Channel: An event producer transmits a message in a channel. Event consumers receive messages subscribing to the channel. It is also known as a Salesforce event bus.
- Event consumer: The subscriber to a channel receives messages from the channel.
Understanding Of Platform Events
It is possible to create Platform Events just like the Salesforce custom objects. The only difference is that the platform events API name has a suffix with __e, whereas the custom objects API name has a suffix with __c.
Platform Events can only support the following custom field types:
- Checkbox
- Date
- Date/Time
- Number
- Text
- Text Area (Long)
REPLAYID System Field
- Salesforce stores platform events for 24 hours. You can also retrieve stored events in API clients, not Apex.
- Each event record has a field called ReplayID, which is populated by the system after the event is published.
What Are The Steps To Create Platform Events?
- Go to Setup and search for Platform Events in the Quick Find Box.
- Click on the New Platform Event Button to create a new platform event.
- Enter the Platform Event details like Label, Description, and Publish Behavior.
Publish Behavior are of 2 types :
- Publish Immediately
- It doesn’t respect transaction boundaries & can not be rolled back.
- Events will be published even if the transaction is failed.
- Publish After Commit
- Published only after the transaction commits.
- If a transaction commits, then only the event is published. Moreover, if any error occurs, then the event is not published.
4. Create a Custom Field to Show the Notification from This Field.
Ways For Publishing And Subscribing To Platform Events In Salesforce
Ways for Publishing are:
- Process Builder
- Flows
- Apex
- API (REST/SOAP)
Ways for Subscribing are:
- Process and Flow Builder
- Subscribe to Platform Event Notifications in Lightning components.
- Apex Trigger
- CometD
Now, we will come to publishing platform events using Apex.
Publishing Platform Event Using Apex
Salesforce has a particular class to publish the platform events EventBus, which has methods publish method. Channels can be consumed once events are published.
Code for Publishing Platform Event
Trigger AccountTriggerEvent on Account (after update) {
if(Trigger.isAfter && Trigger.isUpdate){
List notifyList = new List();
String message = ‘Please fill below fields to improve record Quality. {fieldNames}’;
for(Account accObj : Trigger.new){
//Check if these fields are not null or empty
if(accObj.Phone == null || accObj.AnnualRevenue == null || accObj.AccountNumber == null){
//Instantiating platform event
Notification_Event__e eventObj = new Notification_Event__e();
//Put the value in the platform event fields
String emptyFieldsName = ‘\r\n’;
if(accObj.Phone == null){
System.debug(‘Inside If line 15’);
emptyFieldsName +=’Phone’+’\r\n’;
}
if(accObj.AnnualRevenue == null){
System.debug(‘Inside If line 20’);
emptyFieldsName += ‘Annual Revenue’+’\r\n’;
}
if(accObj.AccountNumber == null){
System.debug(‘Inside If line 25’);
emptyFieldsName += ‘AccountNumber’+”;
}
String finalMsg = message.replace(‘{fieldNames}’,emptyFieldsName);
System.debug(’emptyFieldsName>.>>>’+emptyFieldsName);
system.debug(‘finalMsg => ‘+ finalMsg);
eventObj.Message__c = finalMsg;
System.debug(‘Event Message>>>>’+eventObj.Message__c);
//add the obj in the list
notifyList.add(eventObj);
}
}
//Publish event
try{
if(notifyList.size()>0)
EventBus.publish(notifyList);
}catch(Exception e){
}
}
}
Subscribing Platform Event
In this blog, we must use lightning Emp API to listen to platform event messages in the lightning component.
So, what is the Emp API?
Lightning empApi module provides required access to methods for subscribing to the streaming channels and listening to the events’ messages.
For listening to platform event messages in Lightning Web Component, you can import the methods related to the Lightning/empApi module in your Javascript file using the syntax below.
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from ‘lightning/empApi’ ;
Now, we will subscribe platform event using the below Lightning component ‘showNotification.cmp’:
.toastMessage.forceActionsText{
white-space : pre-line !important;
}
showNotificationController.js
({
doInit : function(component, event, helper) {
var channel = ‘/event/Notification_Event__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));
//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) {
});
const errorHandler = function (message) {
console.error(“Received error “, JSON.stringify(message));
};
empApi.onError(errorHandler);
}
})
Add this Lightning Component to the Account Record Page.
Now let’s check the result: Update any records in which one or more fields inside this list (Phone, Annual Revenue) is empty.
Conclusion
Communicating changes and responding to events can be simplified with Platform Events. They are used to overcome Salesforce Governor Limits.
The developers can use these events to change the rules of the game and process at a faster rate, within the Governor’s limits.
They’re secure and scalable, and one can easily define various fields to personalize the Platform Event data.
A platform event is added with an _e suffix for the event’s API name. It is impossible to roll back the published Platform Events, and all the fields for Platform Events are read-only by default.
Do you want to process at a faster rate, within the Governor’s limits? Cloud Analogy is one of the top-notch, certified Salesforce Consulting Companies offering valuable business advice and assisting you throughout your Salesforce journey.
We provide cost-effective Salesforce Consulting services to help your business grow in countless ways. Get connected to our experienced and certified team at Cloud Analogy, and get started with your project today.
Follow us on our Social Media platforms, YouTube, LinkedIn, Instagram, Facebook and Twitter, to stay updated with the latest technology and trends.
Thank you for reading!
Nitish Bhardwaj
Salesforce Principal Consultant | Chief Information Officer
An experienced Salesforce.com professional with 5+ years of experience in consulting on and delivering Salesforce projects for mid size, large and very large customers.Hire the best Salesforce Implementation Partner. Choose certified Salesforce Implementation Experts from Cloud Analogy now.