Working with Salesforce Platform Events involves creating, publishing, and subscribing to events within the Salesforce ecosystem. It can involve writing a combination of Apex and JavaScript, the later when you make use of Lightning Web Components (LWC).
Here are step-by-step examples of how to work with Salesforce Platform Events
Use Case #1: Order Status Update
Imagine you’re managing an e-commerce application, and you want to notify other systems in real-time whenever the status of an order changes.
Step 1: Create a Platform Event:
- In Salesforce, go to Setup.
- In the Quick Find box, type “Platform Events” and select “Platform Events”.
- Click “New Platform Event.”
- Define the Event Label (e.g., “Order_Status_Event”).
- Configure any custom fields you want to include in the event (e.g., Order ID, New Status, Timestamp). You can add up to 100 custom fields and also define validation rules for the event fields.
- Save the platform event.
Step 2: Publish an Event:
- In Apex code or a Flow, create a logic that triggers an event when an order status changes.
- Instantiate the platform event object and set the custom fields’ values.
- Use the
Database.insert()
method to publish the event.
Here’s a simplified example in Apex:
// Trigger to publish an event when order status changes
trigger OrderStatusTrigger on Order__c (after update) {
List<Order_Status_Event__e> eventsToPublish = new List<Order_Status_Event__e>();
for (Order__c order : Trigger.new) {
if (order.Status__c != Trigger.oldMap.get(order.Id).Status__c) {
Order_Status_Event__e event = new Order_Status_Event__e();
event.Order_ID__c = order.Id;
event.New_Status__c = order.Status__c;
eventsToPublish.add(event);
}
}
if (!eventsToPublish.isEmpty()) {
Database.insert(eventsToPublish);
}
}
Step 3: Subscribe to an Event:
- Create an event subscriber that listens for the published event.
- Create a trigger or process to handle the event data when the event is received.
Here’s a simplified example of subscribing to the event:
// Trigger to handle the event when it's received
trigger OrderStatusEventTrigger on Order_Status_Event__e (after insert) {
List<Order__c> ordersToUpdate = new List<Order__c>();
for (Order_Status_Event__e event : Trigger.new) {
Order__c order = new Order__c(Id = event.Order_ID__c);
order.Status__c = event.New_Status__c;
ordersToUpdate.add(order);
}
if (!ordersToUpdate.isEmpty()) {
update ordersToUpdate;
}
}
In this example, whenever an order’s status changes, a Platform Event is published. Subscribers (like the OrderStatusEventTrigger
above) listen for these events and take action, such as updating records or triggering other processes, like sending the Order information to external systems via callout.
Step 4: Monitor and Manage Platform Events:
You can monitor published events and their status using the Salesforce Event Monitoring feature. You can also use the Salesforce Event Monitoring REST API to retrieve event data.
Use Case #2: Subscribe to Platform Event from Lightning Web Component (LWC)
Subscribing to and reacting to Salesforce Platform Events from a Lightning Web Component (LWC) involves a combination of JavaScript, Apex. Here’s a step-by-step guide on how to achieve this:
Step 1: Create a Platform Event:
Before you can subscribe and react to a Platform Event, make sure you have created a Platform Event as explained in the Use Case #1.
Let’s call it “Custom_Event__e” with a custom field named “Message__c”
Step 2: Create an LWC to Subscribe to the Platform Event:
Create a new Lightning Web Component to subscribe to the Platform Event and display the message when it is received.
<!-- eventSubscriberLWC.html -->
<template>
<lightning-card title="Event Subscriber">
<div class="slds-m-around_medium">
<p>{message}</p>
</div>
</lightning-card>
</template>
// eventSubscriberLWC.js
import { LightningElement, wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import CUSTOM_EVENT from '@salesforce/messageChannel/Custom_Event__c';
export default class EventSubscriberLWC extends LightningElement {
message = '';
@wire(MessageContext)
messageContext;
connectedCallback() {
this.subscribeToEventChannel();
}
subscribeToEventChannel() {
if (this.messageContext) {
const messageCallback = (response) => {
this.handleMessage(response);
};
subscribe(this.messageContext, CUSTOM_EVENT, messageCallback);
}
}
handleMessage(response) {
this.message = response.message.data.payload.Message__c;
}
}
Step 3: Wire the LWC Component:
To use this LWC, add it to a Lightning Page or App Builder. When a Platform Event of type “Custom_Event__e” is published with a message, this component will subscribe to it and display the message. This allows users to interact with the component and see real-time updates based on the subscribed events.
Step 4: Publish the Platform Event:
To test your subscription, you can publish a Platform Event using Apex, Trigger Flow, or other methods within your Salesforce org. Make sure to include the “Message__c” field with the desired message.
Here’s an example of how to publish a Platform Event using Apex:
// Apex Class to Publish a Platform Event
public class PlatformEventPublisher {
public static void publishCustomEvent(String message) {
Custom_Event__e customEvent = new Custom_Event__e(Message__c = message);
EventBus.publish(customEvent);
}
}
You can call this Apex method to publish a custom event with a message.
You can also use an Apex Trigger like we did in Use Case #1.
Step 5: Test:
When you publish the Platform Event with a message, your LWC component will subscribe to it, and the message will be displayed in the Lightning Card.
This is a basic example of how to subscribe to and react to a Platform Event using an LWC in Salesforce. Depending on your use case, you can extend this example to perform more complex actions when events are received.
Please note that this is a simplified use case, and you might need to handle additional considerations such as error handling, security, and data processing based on your specific requirements.
Conclusion
Salesforce Platform Events provide a powerful mechanism for real-time data integration and communication within Salesforce and external systems. By creating, publishing, and subscribing to events, you can enable seamless and efficient data sharing across your applications, enhancing user experiences and driving business agility.
Thanks for reading!
Keep tuned for more in-depth information about this and other topics.