trailhead

Learning Objectives

After completing this unit, you’ll be able to:
  • Define a platform event.
  • Describe how platform event messages can be published.
  • Use an Apex method to publish an event.
  • Publish an event using REST API by inserting an sObject.

Define and Publish Platform Events

Now that you understand what platform events are and when they’re used, let’s get hands-on with defining a platform event! Remember the Cloud News agency? Let’s create a platform event definition that holds the data of news events.

Define a platform event named Cloud News:

  1. From Setup, enter Platform Events in the Quick Find box, then select Platform Events.
  2. On the Platform Events page, click New Platform Event.
  3. For Label, enter Cloud News.
  4. For Plural Label, enter Cloud News.
  5. For Description, enter Cloud news events deliver news at your fingertips.
  6. Click Save.
  7. In the Custom Fields & Relationships related list, click New.
  8. Select Text, and click Next.
  9. For Field Label/Name, type Location.
  10. For Length, type 100. Keep the defaults for the other fields and leave the Description field empty. Click Save.
  11. Follow steps 7, 8, and 9 to add the next two fields:
    Field Label/Name Field Type
    Urgent Checkbox
    News Content Text Area (Long)

For the Cloud News event that you just defined, you created fields of various types, such as a text field or a checkbox. All field types that platform events support are:

  • Checkbox
  • Date
  • Date/Time
  • Number
  • Text
  • Text Area (Long)

Event Retention and ReplayId System Field

Salesforce stores platform events for 24 hours. You can retrieve stored events in API CometD clients but not in Apex. You can retrieve all stored events, or you can specify the replay ID of an event as the baseline for the retrieved portion of events.

Even though Salesforce retains event records temporarily, you can’t query them through SOQL or SOSL. Similarly, you can’t use event records in the user interface in reports, list views, and search. You can retrieve past events only when subscribing in CometD and using a ReplayId option. We show you how to subscribe to events in the next unit.

Each event message is assigned an opaque ID contained in the ReplayId field. The ReplayId field value, which is populated by the system, refers to the position of the event in the event stream. Replay ID values are not guaranteed to be contiguous for consecutive events. For example, the event following the event with ID 999 can have an ID of 1,025. A subscriber can store a replay ID value and use it on resubscription to retrieve events that are within the retention window. For example, a subscriber can retrieve missed events after a connection failure. Subscribers must not compute new replay IDs based on a stored replay ID to refer to other events in the stream.

API Name Suffix

When you create a platform event, the system appends the __e suffix to create the API name of the event. For example, for the Cloud News event, the API name is Cloud_News__e. Use the API name whenever you refer to the event programmatically, for example, in Apex, REST API, and Enterprise API.

Publish Events

If your app is on the Salesforce platform, you can publish events using an Apex method or with declarative tools, such as Process Builder or the Cloud Flow Designer. If your app is an external app, you can publish events using Salesforce APIs.

Publish Event Messages Using Apex

To publish event messages, you create an instance of the event and pass it to the EventBus.publish method.

The following example creates one event of type Cloud_News__e, publishes it, and then checks whether the publishing was successful or encountered errors. The EventBus.publish() method returns a Database.SaveResult object, which contains the result of the publishing. If isSuccess() returns true, the event was published in the Salesforce event bus. Otherwise, the event encountered errors which are returned in the Database.Error object.

// Create an instance of the event and store it in the newsEvent variable
Cloud_News__e newsEvent = new Cloud_News__e(
           Location__c='Mountain City', 
           Urgent__c=true, 
           News_Content__c='Lake Road is closed due to mudslides.');

// Call method to publish events
Database.SaveResult sr = EventBus.publish(newsEvent);

// Inspect publishing result 
if (sr.isSuccess()) {
    System.debug('Successfully published event.');
} else {
    for(Database.Error err : sr.getErrors()) {
        System.debug('Error returned: ' +
                     err.getStatusCode() +
                     ' - ' +
                     err.getMessage());
    }
}

To publish more than one event in the same call, add your events to a list of events, and pass the list to the EventBus.publish() method. The output of this method is an array of Database.SaveResult objects: one for each published event. EventBus.publish() can publish some passed-in events, even when other events can’t be published due to errors. The EventBus.publish() method doesn’t throw exceptions caused by an unsuccessful publish operation. It is similar in behavior to the Apex Database.insert() method when called with the partial success option.

// List to hold event objects to be published.
List<Cloud_News__e> newsEventList = new List<Cloud_News__e>();
// Create event objects.
Cloud_News__e newsEvent1 = new Cloud_News__e(
           Location__c='Mountain City', 
           Urgent__c=true, 
           News_Content__c='Lake Road is closed due to mudslides.');
Cloud_News__e newsEvent2 = new Cloud_News__e(
           Location__c='Mountain City', 
           Urgent__c=false, 
           News_Content__c='Small incident on Goat Lane causing traffic.');
// Add event objects to the list.
newsEventList.add(newsEvent1);
newsEventList.add(newsEvent2);

// Call method to publish events.
List<Database.SaveResult> results = EventBus.publish(newsEventList);

// Inspect publishing result for each event
for (Database.SaveResult sr : results) {
    if (sr.isSuccess()) {
        System.debug('Successfully published event.');
    } else {
        for(Database.Error err : sr.getErrors()) {
            System.debug('Error returned: ' +
                        err.getStatusCode() +
                        ' - ' +
                        err.getMessage());
        }
    }       
}
Note

Note

The Salesforce platform provides allocations for how many events you can define in your org, and how many event records you can publish in an hour. Also, because event publishing is equivalent to a DML insert operation, DML limits and other Apex governor limits apply. For more information see the Resources section.

Publish Event Messages Using Clicks

To publish event messages without code, use the record creation functionality in a process or flow.

This screenshot shows a sample Create a Record action in Process Builder that publishes a Cloud News event message. Basically, set Record Type to the platform event that you want to publish (Cloud News), then set the values for the event.

The Create a Record action in Process Builder is set to the Cloud News record type. The fields of the Cloud News event are filled.

Similarly, you can publish a platform event message with a flow. Configure a Record Create element to create an instance of the platform event (Cloud_News__c), then set the values for the event. To set the value of a Boolean field, such as Urgent__c, use {!$GlobalConstant.True}.

Publish Event Messages Using Salesforce APIs

External apps use an API to publish platform event messages. You publish events by creating records of your event in the same way that you insert sObjects. You can use Salesforce APIs to create platform event records, such as SOAP API, REST API, or Bulk API.

For example, for the Cloud News event, you can publish event notifications by inserting Cloud_News__e records. The following example creates one event of type Cloud_News__e in REST API.

sObject REST endpoint:

/services/data/v40.0/sobjects/Cloud_News__e/

Request body for a POST request:

{
   "Location__c" : "Mountain City",
   "Urgent__c" : true,
   "News_Content__c" : "Lake Road is closed due to mudslides."
}

After the platform event record is created, the REST response looks like this output. Headers are deleted for brevity.

HTTP/1.1 201 Created 

{   
   "id" : "e00xx000000000B",
   "success" : true,
   "errors" : [ ],
   "warnings" : [ ] 
}

You can use any REST API tool or an HTTP client app to make REST API calls. For example, you can use Workbench by following these steps.

  1. Log in to your Trailhead DE org.
  2. Open a new tab and navigate to Workbench at https://workbench.developerforce.com/login.php
  3. For Environment, select Production.
  4. For API Version, select the highest available number.
  5. Select I agree to the terms of service.
  6. Click Login with Salesforce.
  7. On the next screen, click Allow.
  8. In the top menu, select utilities | REST Explorer.
  9. Click POST.
  10. Replace the URI with:
    /services/data/v40.0/sobjects/Cloud_News__e
  11. For the Request Body, add the following body in JSON format.
    {
       "Location__c" : "Mountain City",
       "Urgent__c" : true,
       "News_Content__c" : "Lake Road is closed due to mudslides."
    }
  12. Click Execute.

    The response that Salesforce returns after posting the event looks similar to the following.

    {
      "id" : "e00xx0000000001AAA",
      "success" : true,
      "errors" : [ ],
      "warnings" : [ ]
    }
    

Alternatively, you can publish an event in SOAP API through the create() call or in Bulk API using batch jobs.

Platform Events and Transactions

Unlike with custom objects, platform events aren’t processed within database transactions in the Salesforce platform. As a result, published platform events can’t be rolled back. Note the following:

  • The allOrNoneHeader API header is ignored when you publish platform events through the API.
  • The Apex setSavepoint() and rollback() Database methods aren’t supported with platform events.

When you publish platform events, DML limits and other Apex governor limits apply.

Now that you’ve seen how to define and publish events, let’s see how to subscribe to them!

retargeting