Skip to content

ProjectReferral routing, access and alerts

  • Industry

    Healthcare

  • Cloud

    Apex, LWC, Flow

  • Role

    Lead developer

The requirement

When a referral becomes Urgent, the assigned coordinator gets two things: a bell notification in Salesforce that opens the referral, and an email. This is the kind of rule that changes wording and recipients often and has no complicated logic, so it is built as a record-triggered Flow that an admin can maintain, and the Apex alternative is shown further down for comparison.

The Flow

FlowReferral_Urgent_NotifyRecord-triggered, after save
AssignedDefaultFaultStartReferral__c, whenupdated to meet:Priority is UrgentGet notificationtypeUrgent_ReferralCoordinatorassigned?Assigned_Coordinator__cis not emptySend CustomNotificationBell to thecoordinator, opens thereferralSend Email AlertReferral_Urgent_AlertEndEndNobody to notifyAdd a noteReferral_Note__c withthe fault messageEnd

Drawn to look like Flow Builder's canvas. This is the design of the Flow, not an export from an org.

How it is configured

Setting Value
Object Referral__c
Trigger A record is created or updated
Entry condition Priority__c Equals Urgent
Run the flow Only when a record is updated to meet the condition requirements, so it fires when a referral becomes Urgent and not on every later save
Optimise for Actions and related records (after save), because it sends messages and writes a related record
Notification action Send Custom Notification: type {!NotificationType.Id}, recipients {!$Record.Assigned_Coordinator__c}, target {!$Record.Id}, title and body from text templates
Email action Email Alert Referral_Urgent_Alert, record {!$Record.Id}, recipient set on the alert as the Assigned Coordinator user field
Fault path From the notification action: Create Records, a Referral_Note__c on the same referral holding {!$Flow.FaultMessage}

Why it works the way it does:

  • The entry condition does the filtering. The Flow never runs for routine referrals, which costs nothing and keeps the logic out of the canvas.
  • The Flow sees the trigger’s work. The order of execution runs before-save Apex first, then after-save Flows. By the time the Flow starts, the before trigger has already picked the coordinator, so Assigned_Coordinator__c is set in the same transaction.
  • The Decision is a real branch. If the routing rule found nobody (an empty region), there is no recipient and the Flow ends quietly rather than failing the save.
  • Fault paths are designed, not discovered. A custom notification can fail (an invalid recipient, a deleted notification type). The fault connector leaves a visible note on the referral instead of rolling back the save or vanishing silently.
  • Bell and email are two actions, one with a notification type that admins configure in Setup (Custom Notifications, with Desktop and Mobile delivery), one with an email alert that carries the template and recipients.

The same thing in Apex

The Flow is the right default here. The Apex version exists for the cases where it is not, and it is worth knowing what it takes. Pick one owner for a behaviour: running the Flow and this class together would send every coordinator two bells and two emails.

First, detect the moment a referral becomes Urgent (a new helper beside the others in ReferralChanges):

Illustrative: rebuilt for this site, not client codeReferralChanges.cls (addition)
    public static Boolean becameUrgent(Referral__c r, Map<Id, Referral__c> oldMap) {
      return r.Priority__c == 'Urgent' && changed(r, oldMap, Referral__c.Priority__c);
  }

Then notify, in bulk, from the after-update handler:

Illustrative: rebuilt for this site, not client codeUrgentReferralNotifier.cls
public with sharing class UrgentReferralNotifier {
  private static final String TYPE_NAME = 'Urgent_Referral';

  public static void notify(List<Referral__c> urgent) {
      List<Referral__c> toNotify = new List<Referral__c>();
      for (Referral__c r : urgent) {
          if (r.Assigned_Coordinator__c != null) toNotify.add(r);
      }
      if (toNotify.isEmpty()) return;

      // One query for the notification type, however many referrals.
      Id typeId = [SELECT Id FROM CustomNotificationType
                   WHERE DeveloperName = :TYPE_NAME WITH USER_MODE LIMIT 1].Id;

      List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
      for (Referral__c r : toNotify) {
          Messaging.CustomNotification bell = new Messaging.CustomNotification();
          bell.setNotificationTypeId(typeId);
          bell.setTargetId(r.Id);
          bell.setTitle('Urgent referral ' + r.Name);
          bell.setBody('Needs triage today. Region: ' + r.Region__c + '.');
          bell.send(new Set<String>{ r.Assigned_Coordinator__c });
          mails.add(email(r));
      }
      Messaging.sendEmail(mails); // a single call for every message
  }
}
Illustrative: rebuilt for this site, not client codeUrgentReferralNotifier.cls (email)
    private static Messaging.SingleEmailMessage email(Referral__c r) {
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      mail.setTargetObjectId(r.Assigned_Coordinator__c); // a User, so no Contact is needed
      mail.setSaveAsActivity(false);                       // required when the target is a User
      mail.setSubject('Urgent referral ' + r.Name);
      mail.setPlainTextBody(
          'Referral ' + r.Name + ' was marked Urgent and is waiting in your region (' + r.Region__c + ').\n' +
          URL.getOrgDomainUrl().toExternalForm() + '/' + r.Id
      );
      return mail;
  }

What the Apex version has to carry that the Flow gave for free:

  • No bulk send for bell notifications. Each notification is its own send call, so a bulk update of urgent referrals makes one call per referral. Check the current limits in the Apex Developer Guide before using this on a large update.
  • Email is bulkified, bell is not. Messaging.sendEmail takes the whole list in one call, and it counts against the daily email limit.
  • Failures are yours. send can throw (an invalid recipient, a missing notification type), and it runs inside the save transaction. Catch it, or a notification problem fails the referral update. The Flow’s fault path is the declarative version of this try/catch.
  • Templates. For anything longer than a few lines, use an email template (setTemplateId plus setWhatId) so wording stays editable outside code.
  • Testing. Email sending is not visible to assertions in a test beyond Limits.getEmailInvocations(), so keep the message-building in a method that returns the message and test that.

Flow or Apex?

Choose a Flow when Choose Apex when
An admin should own the wording, recipients and entry criteria The rule is shared by several entry points (trigger, batch, API) and must be one implementation
The logic is a short chain of decisions and actions Loops, maps and algorithms are needed, for example the routing rule’s least-loaded pick
The volume is ordinary record-by-record edits Bulk loads must stay inside tight limits and you need to control the order of queries and DML
A visual map of the process is part of the documentation You need unit tests with assertions on each step and a diff-friendly code review
Failure should be handled with a fault path and a note Failures need retries, partial success or custom logging

In this project the split is: Apex for the decisions (routing, access, change detection) because they are algorithmic and tested, and Flow for the announcement because wording and recipients are a business decision that should not need a deployment.

Built with the Salesforce Lightning Design System. Not affiliated with Salesforce.

App Launcher