How To Register For A Platform Event Using A Trigger

Let’s explore the process of subscribing to Platform Events through Triggers.

We have the capability to trigger a Platform Event from Process Builder, Flow, Apex, and API. Similarly, we can subscribe to the Platform Event using Process Builder, Flows, Apex Triggers, Lightning Components, and CometD.

In this blog post, I will guide you on subscribing to the Platform Event using an Apex Trigger.

Platform Event using an Apex Trigger.

Before we look into this example we need to make sure that the Platform Event is created.

Just like how we have the API name of the custom object ending with __c for a Platform Event the API name ends with __e.

Before you use the snippet, create a Platform event with the fields mentioned in the below Trigger.

Now am gonna use that API name and write a Trigger on that, hence in the below snippet you will find the API name of the Platform Event where we usually specify the Sobject name.

trigger OrderEventTrigger on Order_Event__e (after insert) {    
    //loop through all the records in the list
    for (Order_Event__e event : Trigger.New) {
    	//debug fields of the platform event
		System.debug(' 🚀 ' + event.Account_Id__c );
		System.debug(' 🚀 ' + event.Amount__c );
		System.debug(' 🚀 ' + event.Opportunity_Id__c );        

To inspect the logs, it’s essential to establish a new Trace Flag for the Automated Process user. Follow these steps to create a Trace Flag for the Automated Process user:

  • Go to Setup.
  • Use Quick Find to search for “Debug Logs.”
  • Click on the “New” button.
  • Set the Traced Entity Type to “Automated Process.”
  • Fill in the other required values for the fields.
  • Now, trigger the Platform Event, and you’ll find the corresponding entries in the debug logs.