How To Register For A Platform Event Using A Trigger

Explore the process of subscribing to Platform Events through Triggers.

We can fire a Platform Event from Process Builder, Flow, Apex, and API.

Likewise we can also subscribe to the Platform Event using Process Builder, Flows, Apex Triggers, Lightning Components, and Comet D.

In this blog post am gonna walk you through how can we subscribe to the 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 examine the logs, it is 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:

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