はじめに
今回はApexでカスタム通知をやってみます。標準機能でも通知は来ますが(承認申請されたときなど)、特定の状況でユーザに通知をしたいときにはApexで通知を出来ます。
カスタム通知を作成
設定の「カスタム通知」からカスタム通知を作成します。通知を行う媒体を選択できます。
Apexからカスタム通知を呼び出し
CustomNotificationTypeから先ほど作成したカスタム通知を取得します。
setTitle()とsetBodyで通知の内容を指定します。setTargetIdに対象のレコードのIdを入れます。
最後にTry-catchのなかのsend()で通知をしたいユーザのIdを入れて通知を送信します。
CustomNotificationType notificationType =
[SELECT Id, DeveloperName
FROM CustomNotificationType
WHERE DeveloperName='MyCustomNotification'];
// Create a new custom notification
Messaging.CustomNotification notification = new Messaging.CustomNotification();
// Set the contents for the notification
notification.setTitle('レコードが更新されました');
notification.setBody('The notifications are coming from INSIDE the Apex!');
// Set the notification type and target
notification.setNotificationTypeId(notificationType.Id);
notification.setTargetId(newRec.Id);
// Actually send the notification
try {
notification.send(new Set<String> { Userinfo.getUserId() });
}
catch (Exception e) {
System.debug('Problem sending notification: ' + e.getMessage());
}
ものの数分で実装が完了しました。このくらいであればプロセスビルダーでも実現できますが、より複雑な条件で通知をしたい場合はApexでもできるので選択肢の幅は広がりますね。