Ticker

6/recent/ticker-posts

Header Ads Widget

Send Custom Notifications Using Apex

Winter 21 release is bringing many great features for us. We are all excited. Here are some of my posts covering some of the important features that will come with the Winter 21 release -
In today's post, I will be discussing about the feature which will allow us to send custom notifications using Apex. 

Introduction of Custom Notification

Custom notifications are the customized notifications that can be sent when some action happened with Salesforce. For example, every time a new knowledge article is published, we can publish a custom notification to all the users/selected users. These notifications are real-time i.e. users don't require to refresh their existing page to get the notification. On the same only, these notifications will be presented on the bell icon.

Create Custom Notification

  • Type 'Notification' in the setup search
  • Click 'Custom Notifications' under 'Notification Builder'
  • Click New
  • Enter the name for example - "Knowledge Notification"
  • Select the channels (Mobile and/or Desktop).

Apex Code to Send Notification

//New Class introduced to deal with Custom Notifications
Messaging.CustomNotification singleNotification =
                        new Messaging.CustomNotification();
//Required - Setting up the Body
singleNotification.setBody('New Article is published');
//Required - Setting up the title
singleNotification.setTitle('Check the new article!');
//Optional - Who is sending this notification
singleNotification.setSenderId(Userinfo.getUserId());
//Fetching the custom notification created and using that id
CustomNotificationType type = [ SELECT Id
                                FROM CustomNotificationType
                                WHERE Name = 'Knowledge_Notification'];
singleNotification.setNotificationTypeId(type.id);
//Setting up the target record for the notification. This record will
//open when someone click on the notification
singleNotification.setTargetId(<SALESFORCE_RECORD_ID>);
//Who this notification will go. In real-world scenarios, notifications
//will go to some group members.
//So need to query the group and use group Id here
singleNotification.send(new Set<String> { Userinfo.getUserId() });

With this new object Messaging.CustomNotification, we don't require to do complex work to send notification from Apex anymore. I hope this will help you. 

Please provide your feedback. 

Post a Comment

4 Comments

  1. It's surely a great feature , thanks for documenting it so well Sudipta..

    ReplyDelete
  2. Sudipta, any example to send notification to a Lightning record page or Component with parameters? Basically using 'pageReference' option.

    ReplyDelete
    Replies
    1. This notification will work at the global level. So same notification can be available in read-life in Lighting record page or component. You do not need any custom coding.

      Delete