11

My customer wants to send bell notifications whenever you add an Attendant to an Event.

Is there a way to create custom bell notifications via apex code?

If not, is it possible to achieve this without any mail provider integration?

enter image description here

4
  • 1
    I am not sure if it is the best option, but I had a very similar requirement. I archived thru an apex that create a FeedItem.
    – m Peixoto
    Commented Apr 8, 2019 at 13:57
  • @mPeixoto How did you achieve that? Cause I'm not finding anything usefull for my particular case
    – molinet
    Commented Apr 8, 2019 at 14:11
  • You could create a FeedItem and the Parent ID will be the user that will receive the Bell Notification. In this case, a chatter will be created mentioned the user and a notification will be created
    – m Peixoto
    Commented Apr 8, 2019 at 14:37
  • Another approach, if you want to use a Chatter Post. Could you trigger a Process Builder when a new attendant is created? So, you could use Process Builder to create a chatter post.
    – m Peixoto
    Commented Apr 8, 2019 at 14:38

4 Answers 4

5

I am not sure if it is the best approach, but I had a situation very close of that. I needed to create a notification for an user linked with a Case.

    List<FeedItem> FeedItemList = New List<FeedItem>();

    for (Case caseitem : CaseCreateAlert) {

        FeedItem post = new FeedItem();

        post.ParentId = caseitem.OwnerId;
        post.Body = caseitem.Message_To_Alert__c;
        post.Title = 'Case';
        post.LinkUrl = '/lightning/r/Case/' + caseitem.ID + '/view';

    }

    if (FeedItemList.size()>0) {         
            insert FeedItemList;                
    }

This source code is not perfect and it is for reference only. You could have issue if the case owner is a Queue, for example.

4
  • Thanks! I'll try that!
    – molinet
    Commented Apr 8, 2019 at 14:47
  • Welcome, I hope if somebody have a better solution!
    – m Peixoto
    Commented Apr 8, 2019 at 14:48
  • So basically the answer is to create any Chatter post directly to the User, or @mentions would probably work in certain scenarios.
    – Adrian Larson
    Commented Apr 8, 2019 at 16:32
  • 3
    I tried this but it created only Chatter post, no bell notification. Commented Apr 28, 2020 at 9:04
27

From Winter 2021 you will be able to send notifications directly using apex. The below code works with winter 2021 and later.

Id typeId = [SELECT Id FROM CUstomNotificationType WHERE DeveloperName = 'notification type name'].Id;
Messaging.CustomNotification notification = new Messaging.CustomNotification();
notification.setBody('This is body of the custom notification!');
notification.setTitle('Hi this is first notification sent using apex!');
notification.setSenderId(Userinfo.getUserId());
notification.setNotificationTypeId(typeId );
notification.setTargetId('006B0000005hCxzIAE'); // target object id
notification.send(new Set<String> { Userinfo.getUserId() }); // target user id.

Send Custom Notifications from Apex

My Blog post on this: forcetrails.com - send custom notification using-apex

18

You can definitely send Bell Notifications via apex. Andrew Fawcett explained this feature in detail in his article https://andyinthecloud.com/2019/06/30/getting-your-users-attention-with-custom-notifications/.

A month ago I had a task to send a notification to my user when deletion of test data is finished. This is an example code how it was done:

public class MyBellNotification
{   
    public static void notifyCurrentUser(String message)
    {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(Url.getOrgDomainUrl().toExternalForm()
            + '/services/data/v46.0/actions/standard/customNotificationAction');
        req.setMethod('POST');
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
        req.setHeader('Content-Type', 'application/json');
        CustomNotificationActionInput input = new CustomNotificationActionInput();
        input.customNotifTypeId = '0ML0b000000KyjGGAS';
        input.recipientIds = new List<String>{UserInfo.getUserId()};
        input.title = 'Test Data Operation Completed';
        input.body = message;
        input.targetId = '0ML0b000000KyjGGAS';
        CustomNotificationAction action = new CustomNotificationAction();
        action.inputs = new List<CustomNotificationActionInput>{input};
        req.setBody(JSON.serialize(action));
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
    }

    public class CustomNotificationAction
    {
        public List<CustomNotificationActionInput> inputs { get; set; }
    }

    public class CustomNotificationActionInput
    {
        public String customNotifTypeId { get; set; }
        public List<String> recipientIds { get; set; }
        public String title { get; set; }
        public String body { get; set; }
        public String targetId { get; set; }
    }
}

A few things to note:

  1. You need to define a new Notification Type under the Setup menu.
  2. Get the Id of the Notification Type you created. Just run the following query in the Developer Console's Query Editor SELECT Id, DeveloperName FROM CustomNotificationType.
  3. Use this ID in the input.customNotifTypeId = '0ML0b000000KyjGGAS'; and input.targetId = '0ML0b000000KyjGGAS'; fields. If you want you can use the id of an Attendant record in the targetId field. It will generate a link to that record in the notification text.
  4. Since this implementation requires an API callout, you cannot perform DML operations in the same transaction prior to calling this code or in triggers. A workaround to this is to define a Queueable class and call that class instead. See below:

public without sharing class Notification implements Queueable, Database.AllowsCallouts { String message;

public Notification(String message)
{
    this.message = message;
}

public void execute(QueueableContext context)
{
    MyBellNotification.notifyCurrentUser(message);
}

}

This is just a use case sample DO NOT USE this lines in your code as you will delete 10,000 accounts from your org:

Database.delete(Database.query('SELECT Id FROM Account LIMIT 10000 WHERE isTestData__c = TRUE'));
System.enqueueJob(new Notification('Records deleted'));
2
  • Hi There, I have tried doing this and it worked great within the sandbox and production during testing. However the process i am using this under triggers the Flow from a commuity page meaning this class runs under a 'Guest User' permissions, whilst it worked for an hour or so it than stopped and dropped out "Session expired or invalid" errors. Appreantly you can't Guest users don't have session Id's anymore and the new API listed before isnt here yet. Any Ideas? Commented Oct 2, 2020 at 15:10
  • Hi @TimChadwick, please see the answer from Rahul Gawale below. It seems that Salesforce has made notification api available directly from apex.
    – Eduard
    Commented Oct 5, 2020 at 9:30
7

You can achieve the bell notification through the new Summer '19 Custom Notifications feature however, it's not triggerable via APEX just yet. I know this doesn't directly answer the question re: APEX, but it's a pretty simple process builder.

https://developer.salesforce.com/blogs/2019/06/get-buildspiration-with-custom-notifications-in-summer-19.html

Upside of this is that you can also deliver these as push notifications to the user's mobile device/watch etc. (so long as they have the Salesforce1 app installed).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .