Andy in the Cloud

From BBC Basic to Force.com and beyond…

Getting your users attention with Custom Notifications

55 Comments

customnotificationsummaryGetting your users attention is not always easy, choosing how, when and where to notify them is critical. Ever since Lightning Experience and Salesforce Mobile came out the notification bell has been a one stop shop for Chatter and Approval notifications, regardless if you are on your desktop or your mobile device.

In beta release at time of writing is a new platform feature known as Notification Manager that allows you to send your own custom notifications to your users for anything your heart desires from the very same locations, even on a users mobile device! This blog dives into this feature and how you can integrate it into your creations regardless if you are a admin click coder, Apex developer or REST API junkie.

Getting Started

The first thing you need to do is define a new Notification Type under the Setup menu. This is a simple process that involves giving it a name and deciding what channels you want the notification to go out on, currently user desktop and mobile devices.

notificationstypes

Once this has been done you can use the new Send Custom Notification action in Process Builder or Flow. This allows you to define the title and body of your notification, along with the target recipients (users, groups, queues and more) along the target record that determines the record the user sees when they click/tap the notification. The following screenshot shows an example of such an Action in Process Builder:-

opportunitycustomnotification

notificationoppty.png

Basically that is all there is to it! You will have in a few clicks empowered yourself with the ability to reach out to not only your users desktop but the actual mobile device notification experience on each of the their mobile devices!  You didn’t have to learn how to write a mobile app, figure out how to do mobile notifications, register things with Google or Apple. I am honestly blown away at how easy and powerful this is!

So it is pretty easy to to send notifications this way from Process Builder processes driven by record updates from the user and also reference field values to customize the notification text. However in the ever expanding world of Platform Events, how do we send custom notifications based on Platform Events?

Sending Custom Notifications for Batch Apex Job Failures

One of my oldest and most popular blog posts discussed design best practices around Batch Apex jobs. One of the considerations it calls out is how important it is to route errors that occur in the background back to the user. Fast forward a bit to this blog, where I covered the new BatchApexError Platform Event as a means to capture and route batch errors (even uncatchable exceptions) in near realtime. It also describes strategy to enabled users to retry failed jobs. What it didn’t really solve, is letting them know something had gone wrong without them checking a custom tab. Let’s change that!

Process Builder is now able to subscribe to the standard BatchApexErrorEvent and thus enables you as an admin to apply filter and routing logic on failed batch jobs. When combined with custom notifications those errors can now be routed to users devices and/or desktops in realtime. While Process Builder can subscribe to events it does have some restrictions on what it can do with the event data itself. Thus we are going to call an autolaunch Flow from Process Builder to actually handle the event and send the custom notification from within Flow. If you are reading this wondering if your Apex code can get in on the action, the answer is yes (ish), more on this later though. The declarative solution utilizes one Process Builder process and two Flows. The separation of concerns between them is shown in the diagram below:-

batchapexeventtonotificationarch

Let’s work from the bottom to the top to understand why I decided to split it up this way. Firstly, SendCustomNotification is a Sub Flow (callable by other Flows) and is a pretty simple wrapper around the new Send Custom Notification action shown above. You can take a closer look at this later through the sample code repository here.

SendCustomNotification

Next the BatchApexErrorPlatformEventHandler Flow defines a set of input variables that are populated from the Process Builder process. These variables match the fields and types per the definition of the Batch Apex Error Event here. The only other thing it does is add the Id of the user that generated the event (aka the user who submitted the failed job) to the list of recipients passed to the SendCustomNotification sub flow above. This could also be a Group Id if you wanted to send the notification further.

batchapexeventhandlerflow.png

Lastly, in the screenshot below you see the Process Builder that subscribes to the Batch Apex Error Event and maps the event field values to the input variables exposed from BatchApexErrorPlatformEventHandler Flow via the EventReference. The example here is very simple, but you can now imagine how you can add other filter criteria to this process that allows you to inspect which Batch Apex job failed and route and/or adjust messaging in the notifications accordingly, all done declaratively of course!

batchapexerrorfrompb.png

NOTE: It is not immediately apparent in all cases that you can access the event fields from Process Builder, since the documentation states them as not supported within formulas. I want to give a shout out to Alex Edelstein PM for Flow for clarifying that it is possible! Check out his amazing blog around all things Flow here. Finally note that Process Builder requires an Object to map the incoming event to. In this case I mapped to a User record using the CreatedById field on the event.

Sending Custom Notifications from Code

The Send Custom Notification action is also exposed via the Salesforce Action REST API defined here (hint hint for Doug Ayers Mass Action tool to support it). You can of course attempt to call this REST API via Apex as well. While there is currently no native Apex Action API, it turns out calling the above SendCustomNotification Flow from Apex works pretty well meanwhile. I have written a small wrapper around this technique to make it a little more elegant to perform from Apex and it also serves to abstract away this hopefully temporary workaround for Apex developers.

new CustomNotification()
    .type('MyNotificationType')
    .title('Fun Custom Notification')
    .body('Custom Notifications are Awesome!')
    .sendToCurrentUser();

The following Apex code results in this notification appearing on your device!

funfromapexnotification.png

This CustomNotification helper class is included in the sample code for this blog and leverages another class I wrote that wraps the native Apex Flow API. I used this wrapper because it allowed me to mock the actual Flow invocation since there is no way as far as I can see to assert the notification was actually sent.

NOTE: When sending custom notifications via declarative tools and/or via code I did confirm in my testing that they are included in the current transaction. Also I recommend you always avoid calling Flow in loops in your Apex code, instead make your Flows take list variables (aka try to bulkify Flows called from Apex). Though not shown in the Apex above, the wrapped Flow takes a list of recipients.

Summary

You can find all the code for this blog in sample code repository here. So there you have it, custom mobile and desktop notifications sent from Process Builder, Flow, Apex and REST API. Keep in mind of course at time of writing this is a Beta feature and thus read the clause in the documentation carefully. Now go forth and start thinking of all the areas you can enable with this feature!

P.S. Check out another new cool feature called Lightning In-App Guidance.

 

 

55 thoughts on “Getting your users attention with Custom Notifications

  1. Pingback: Getting Your Users Attention with Custom Notifications – UnofficialSF

  2. video for implementing above would be very useful.

    • Sorry this is not something I can do right now – you can deploy the code and open Flow and Process Builder and inspect for yourself in the meantime.

  3. Can you please provide each step to create process builder and two flows. (on batch apex error event)

    • Sorry this is not something I can do right now – you can deploy the code and open Flow and Process Builder and inspect for yourself in the meantime.

  4. Hi Andy, thanks for the shout-out to Mass Action Scheduler. I got the hint *wink, wink* and have opened a [feature request to support custom notifications](https://github.com/douglascayers-org/sfdx-mass-action-scheduler/issues/111#issue-470931411).

  5. Hi Andy. Firstly, thanks for being one of the first people writing about the new Send Custom Notification Action in Flow (all others seem to be in Process Builder). I’m trying to work out exactly what is expected in each field of the Flow Action. Can you help?

    Custom Notification Type ID:
    Notification Types get created in a popup window and I cannot find anywhere to grab a record ID

    Recipient IDs:
    This won’t let me input the text variable I’ve stored of the logged in user – and it also moans when I input a user ID. Do you know what is expected?

    Target ID:
    I assume this means a record ID?

    Any guidance much appreciated.

  6. Can you please do it step by step so that we can follow easily

  7. Andy, would you be willing to consider a random act of kindness? I am an unskilled but still designated “salesforce administrator” at my company in Michigan, USA, and we have your DLRS managed app installed on our instance, for some critical functionality. It has stopped working. Might be something completely easy for a trained eye to see and fix. But, of course, Salesforce has pointed us to the managed app source as where we would have to seek our help….so….HELP…….I can’t even further describe the problem, of course. I can just say I can clearly see it is not doing what it is supposed to calculate and do. Would you be willing to call and screen share with me on this issue so that I could show you around ?

    • So sorry I missed this, there has been an issue with notifications on my mobile. Did you raise your issue in the dlrs community chatter group?

  8. Hi Andy, Thank you so much for this detailed post. Instead of hardcoding Notification Type Id / storing in custom meta datatype, I added a Get Record element in the flow and filtered based on CustomNotificationType object- with developername = ‘typename’ and got my TypeId. This is working perfectly fine in the sandbox which I created the flow.

    But When I try to deploy this Flow to other envs, getting this failure mesg – Custom Object Definition ID: bad value for restricted picklist field: CustomNotificationType. Do you have any idea on this? Is this a underlying reason for using custom metadata types in your code..? Any guidance is appreciated.

    • Ah nice, i missed that that object can be queried. So the main reason for the custom metadata type was to lookup the custom notification type id. Since you have worked around this by querying direct, you don’t need the custom metadata type. 🙂

    • Hi chitra, I am getting the same error. Will you be able to resolve it ? if so please let me know the solution

    • Hi Chitra, is this issue of yours already fixed? I’m currently encountering this error as well when I try to deploy.

  9. How to deploy CustomNotificationType using ANT migration tool. I am having a hard time with this.

    • Can you share anymore detail? What have you tried? What is the error? I mainly focus on using sfdx cli so don’t typically use ant anymore.

  10. We are facing the issue that in the meta data there is a hard coded ID within assignmentItems even though a group is selected. Have you tried to deploy the process from above to another instance? In our case, process is not firing. Appreciate your help 🙂

  11. Hi Andrew, Thank you for this detailed descriptions, Do you know if there is way for us to Query or Get from an API all the notifications that have been raised for a user?

  12. Updated this to remove need for custom metadata type. Thanks to the community for this tip!

  13. Hi,

    I tried this out in a dev org and it works great! however whenever I try to deploy to another org I get an error that breaks the deploy:

    “Custom Object Definition ID: bad value for restricted picklist field: CustomNotificationType”

    Any clue on what could cause this? It happens when I deploy the flow by itself or as part of the whole package. I am also using your Jan 11 revision in case that makes a difference.

    • It looks like your using the first version of this example which used a custom metadata type to store the Id of the custom notification. And that that Id has been copied over to production via that custom metadata type and the Id does not reflect a Custom Type Notification in production org? This is my guess anyway. But the good news is! I updated the code to not depend on this approach and now it dynamically fetches the Id at runtime. Check out the latest code. Hope this helps.

      • Hi Andy,
        I am trying to push source in scratch org and it is still giving error ‘Custom Object Definition ID: bad value for restricted picklist field: CustomNotificationType’ .

        Any idea to resolve this error and push this repository in scratch org ?

      • Can you try removing the id from the file before pushing?

  14. I have a requirement to send custom notification to list of Users via Apex code. It that possible do to ?

  15. Hi Andy,

    Great blog post. In your code snippet you are not specifying a targetid, but in the API documentation as well as Process builder and Flow the targetid is required. Am I missing something? I have a requirement where I ‘d like to send bell notifications that are not linked to records, but Process Builder and Flow don’t seem to allow for that. Thoughts?

    Chris

  16. Hi Andy, are there any way that we can change the custom notification icon ?

    Thank you

  17. HI Andy thanks for this…the Notification Recipient…is the Group a group i need to create in Public Groups as admin? or the Groups in the Lightning interface? I used a Public Group but it doesnt notifiy the people in the group…just me! Any ideas?

  18. Thanks Andrew Fawcett. This is really helpful for me.

  19. Pingback: Getting your users attention with Custom Notifications - Salesforce News & Tutorials

  20. Hi Andy.
    I’m trying to deploy a process builder in that I’m sending a custom notification to a public group.
    The recipientId (Group.Id) brought trought the change set process (sandbox: dev to sandbox:hom) like a literal value. It doesn’t seems uses the API name of the group.
    Do you know why this is happening?

  21. Hi Andrew,

    I’m struggling with the target page reference variation of this set via the Messaging.CustomNotification.setTargetPageRef, getting “Invalid parameter value for: targetPageRef” for all the variations I’ve tried. A working example of that posted somewhere would be great.

    See https://salesforce.stackexchange.com/questions/331750/what-is-the-syntax-of-the-string-set-via-settargetpageref-in-the-new-apex-messag. My example is in a community, but others look like they have had trouble in other contexts.

    Thanks,
    Keith

    • Thanks for sharing Keith. As I read the above now it looks solved. Are you good?

      • Yep some progress made. Haven’t got back to this, but suspect that the problem is trying to add “state” that our community uses but that is not included in the LWC PageReference Types documentation.

  22. 1. From the trigger, per transaction, I want to send Custom notifications for 200 Users with different body? Currently, I’m sending in for loop, like below :
    Messaging.CustomNotification obj = new Messaging.CustomNotification();
    obj.send(new set{‘0051y0000025hYaAAI’});
    Is it possiable to bulkify ?

    2. Also, can we check triggered notifications details , in SOQL or in REST ?

  23. Pingback: Bell icon in communities: syntax of the setTargetPageRef string?

Leave a reply to Andrew Fawcett Cancel reply