Custom Notification through Apex

Hi Everyone !!!

Today i am going to discuss one of the feature that is recently in winter 21. As i had previously discussed using custom notification from Process builder and Flows. You can read the blog from here if not read already.

So lets discuss the how can we use custom notification using apex .

  1. Create a custom notifications record.
  2. Write an apex class to query and send custom notification .

Steps to create the Custom notification can be found here in the first section.

Once the Notification is created. We need apex snippet to send notification.

public class SendCustomNotificationHandler {
public static void sendNotifs(){
CustomNotificationType objCustomNotif = [SELECT Id FROM CustomNotificationType
WHERE DeveloperName = 'Send_Notification_When_Oppty_is_Closed_Won_Lost'];
Messaging.CustomNotification sendNotification = new Messaging.CustomNotification();
sendNotification.setBody('Custom Notification -- Winter 21 Release');
sendNotification.setTitle('Custom Notifications By Apex');
sendNotification.setSenderId(Userinfo.getUserId());
sendNotification.setNotificationTypeId(objCustomNotif.id);
sendNotification.setTargetId(Userinfo.getUserId());
sendNotification.send(new Set { Userinfo.getUserId() });
}
}

On running this class using developer console using below code:

SendCustomNotificationHandler.sendNotifs();

Messaging.CustomNotification is the messaging class which we need to call and that will send notification.

Below are parameters that we use :

setBody – Body of the Notifications

setTitle – Title of Notification

setSenderId – One who has sent the Notifications

setNotificationTypeId – Notification which is queried and sent

setTargetId- Object on which we send the notification.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s