Play Games

Search This Blog

Wednesday, February 9, 2022

How to send custom notifications to a user in Salesforce - Salesforce Globe For You

How to send custom notifications to a user in Salesforce - Salesforce Globe For You

Solution: Use the Messaging.CustomNotification class to create, configure, and send custom notifications directly from Apex.

Step 1: create custom notification type by navigating to setup --> Notification Builder --> Custom  Notifications --> New as shown in the image below.



Step 2: Use the sample apex code to send the notification

public class CustomNotificationController {

    public static void sendNotification() {

        List<CustomNotificationType> lstNotificationType = new List<CustomNotificationType>();

        lstNotificationType = [SELECT Id, DeveloperName FROM CustomNotificationType 

                                WHERE DeveloperName='Test_Custom_Notification'];

        Messaging.CustomNotification objNotification = new Messaging.CustomNotification();

        objNotification.setNotificationTypeId(lstNotificationType[0].Id);

        objNotification.setTitle('Testing Custom Notification');

        objNotification.setBody('This is a test Sample Notification');

        objNotification.setTargetId(userInfo.getUserId());

        Set<String> setAddress = new Set<String>();

        setAddress.add(userInfo.getUserId());

        try {

            objNotification.send(setAddress);

        }

        catch (Exception e) {

            System.debug('Exception: ' + e.getMessage());

        }

    }

}

You can call this code from apex trigger or from developer console anywhere.

In this example,its called from developer console

CustomNotificationController.sendNotification();

Output:


Note: This custom notification is available only in Salesforce Lightning experience.

No comments:

Post a Comment