Skip to main content
Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.
Estimación de tiempo

Publish a Platform Event

In this last step, you implement a Chatter Apex trigger that triggers a notification for each post containing the #BearAlert topic.

Implement a Chatter Apex Trigger

  1. Create an Apex trigger named BearAlertTopicAssignmentTrigger:
    1. In Visual Studio Code, under force-app/main/default, right-click the triggers folder and select SFDX: Create Apex Trigger.
    2. Enter BearAlertTopicAssignmentTrigger for the name of the trigger.
    3. Press Enter and then press Enter again to accept the default force-app/main/default/triggers.
  2. Replace the default code with this:
    trigger BearAlertTopicAssignmentTrigger on TopicAssignment (after insert) {
        // Get FeedItem posts only
        Set<Id> feedIds = new Set<Id>();
        for (TopicAssignment ta : Trigger.new){
            if (ta.EntityId.getSObjectType().getDescribe().getName().equals('FeedItem')) {
                feedIds.add(ta.EntityId);
            }
        }
        // Load FeedItem bodies
        Map<Id,FeedItem> feedItems = new Map<Id,FeedItem>([SELECT Body FROM FeedItem WHERE Id IN :feedIds]);
        // Create messages for each FeedItem that contains the BearAlert topic
        List<String> messages = new List<String>();
        for (TopicAssignment ta : [SELECT Id, EntityId, Topic.Name FROM TopicAssignment WHERE Id IN :Trigger.new AND Topic.Name = 'BearAlert']) {
            messages.add(feedItems.get(ta.EntityId).body.stripHtmlTags().abbreviate(255));
        }
        // Publish messages as notifications
        List<Notification__e> notifications = new List<Notification__e>();
        for (String message: messages) {
            notifications.add(new Notification__e(Message__c = message));
        }
        List<Database.SaveResult> results = EventBus.publish(notifications);
        // Inspect publishing results
        for (Database.SaveResult result : results) {
            if (!result.isSuccess()) {
                for (Database.Error error : result.getErrors()) {
                    System.debug('Error returned: ' + error.getStatusCode() +' - '+ error.getMessage());
                }
            }
        }
    }
    Code Highlights:
    • The trigger intercepts all new Chatter posts that contain one or more topics.
    • If a post contains the #BearAlert topic, the trigger publishes the post message as a notification through the standard EventBus utility class. Errors are checked after publication.
  3. Save the file.
  4. Right click on the triggers folder and select SFDX: Deploy Source to Org to deploy your trigger to your org.

Test the Chatter Trigger

Now you can test your work. Create a Chatter post to ensure that it triggers a notification.

  1. From the App Launcher (App launcher icon), find and select Sales, or if the Sales app is already open, refresh the browser.
  2. Click Chatter.
  3. Create a new post with the following content:
    #BearAlert False alarm: It's just a big dog!

At this point, your message appears both as:

  • A notification toast
  • A Chatter post

An image showing a notification being triggered by a Chatter post.

Project Summary

Congratulations, you are now a platform events expert!

Now you know how to define a platform event, how to publish events with Apex, and how to subscribe to events via a Lightning component that uses the lightning/empApi module.

You can apply your newly gained knowledge to build your own event-driven applications.

Comparta sus comentarios sobre Trailhead en la Ayuda de Salesforce.

Nos encantaría conocer su experiencia con Trailhead. Ahora puede acceder al nuevo formulario de comentarios cuando quiera desde el sitio de la Ayuda de Salesforce.

Más información Continuar para compartir comentarios