Skip to content

ProjectReferral routing, access and alerts

  • Industry

    Healthcare

  • Cloud

    Apex, LWC, Flow

  • Role

    Lead developer

Why wrap

The coordinator’s board needs more than a Referral__c row: the patient’s name from a parent, the latest note from a child, a computed age in days, and whether this user may edit the record. Returning the sObject would leak the schema to the component, send fields the UI never shows, and force the JavaScript to dig through Patient__r?.Name paths.

A wrapper class (a DTO) is the contract between Apex and the component: flat, named for the screen, and stable when the data model moves underneath it. If Patient__c becomes a Person Account later, one constructor changes and the LWC does not.

The wrapper classes

Illustrative: rebuilt for this site, not client codeReferralCardDto.cls
public with sharing class ReferralCardDto {
  @AuraEnabled public Id recordId;
  @AuraEnabled public String name;
  @AuraEnabled public String patientName;
  @AuraEnabled public String clinicName;
  @AuraEnabled public String status;
  @AuraEnabled public String priority;
  @AuraEnabled public Boolean isUrgent;
  @AuraEnabled public Boolean canEdit;
  @AuraEnabled public Integer daysSinceRouted;
  @AuraEnabled public String latestNote;

  public ReferralCardDto(Referral__c r, Boolean canEdit) {
      this.recordId = r.Id;
      this.name = r.Name;
      this.patientName = r.Patient__r?.Name;
      this.clinicName = r.Referring_Clinic__r?.Name;
      this.status = r.Status__c;
      this.priority = r.Priority__c;
      this.isUrgent = r.Priority__c == 'Urgent';
      this.canEdit = canEdit;
      this.daysSinceRouted = r.Routed_On__c == null ? null : r.Routed_On__c.date().daysBetween(Date.today());
      this.latestNote = r.Referral_Notes__r.isEmpty() ? null : r.Referral_Notes__r[0].Body__c;
  }
}
Illustrative: rebuilt for this site, not client codeReferralBoardDto.cls
public with sharing class ReferralBoardDto {
  @AuraEnabled public List<ReferralCardDto> cards;
  @AuraEnabled public Integer openCount;
  @AuraEnabled public Integer urgentCount;

  public ReferralBoardDto(List<ReferralCardDto> cards, Map<String, Integer> openByPriority) {
      this.cards = cards;
      this.urgentCount = openByPriority.get('Urgent') ?? 0;
      Integer total = 0;
      for (Integer n : openByPriority.values()) total += n;
      this.openCount = total;
  }
}

Only members marked @AuraEnabled are serialised to the component, so anything that is not marked (a helper, a constructor argument) stays on the server. Public properties would work too. Plain fields are kept here because the class has no logic to put in a getter.

The controller

cacheable=true tells the platform it may serve the result from the client cache and call the method from a @wire. The price: a cacheable method cannot do DML, so the write goes in a second, non-cacheable method.

Illustrative: rebuilt for this site, not client codeReferralBoardController.cls
public with sharing class ReferralBoardController {

  @AuraEnabled(cacheable=true)
  public static ReferralBoardDto getBoard(Integer maxRows) {
      try {
          Integer cap = Math.min(Math.max(maxRows ?? 25, 1), 100);
          Id me = UserInfo.getUserId();
          List<Referral__c> rows = ReferralSelector.openForCoordinator(me, cap);
          Map<Id, Boolean> editable = editableByRecord(me, rows);

          List<ReferralCardDto> cards = new List<ReferralCardDto>();
          for (Referral__c r : rows) {
              cards.add(new ReferralCardDto(r, editable.get(r.Id) == true));
          }
          return new ReferralBoardDto(cards, ReferralSelector.openCountsByPriority(me));
      } catch (Exception e) {
          throw toAura(e);
      }
  }

  @AuraEnabled
  public static void acknowledge(Id referralId) {
      try {
          List<Referral__c> found = ReferralSelector.byIds(new Set<Id>{ referralId });
          if (found.isEmpty() || found[0].Status__c != ReferralStatus.NEW_REFERRAL) return;
          Database.update(new Referral__c(Id = referralId, Status__c = ReferralStatus.TRIAGED), AccessLevel.USER_MODE);
      } catch (Exception e) {
          throw toAura(e);
      }
  }
}

Two details a reviewer will look for:

  • The server owns the limits. maxRows comes from the component, so it is clamped (1 to 100) before it reaches LIMIT. Never trust a number that crossed the wire.
  • canEdit is computed, not guessed. UserRecordAccess reports what the platform would let this user do, including access granted by the Apex sharing on the next page, so the button state always matches the real permissions.
Illustrative: rebuilt for this site, not client codeReferralBoardController.cls (helpers)
    private static Map<Id, Boolean> editableByRecord(Id userId, List<Referral__c> rows) {
      Map<Id, Boolean> editable = new Map<Id, Boolean>();
      if (rows.isEmpty()) return editable;
      Set<Id> recordIds = new Map<Id, Referral__c>(rows).keySet();
      // UserRecordAccess answers for at most 200 record Ids per query: the cap above keeps us under it.
      for (UserRecordAccess a : [
          SELECT RecordId, HasEditAccess FROM UserRecordAccess
          WHERE UserId = :userId AND RecordId IN :recordIds
      ]) {
          editable.put(a.RecordId, a.HasEditAccess);
      }
      return editable;
  }

  private static AuraHandledException toAura(Exception e) {
      // Full detail for the log, a safe sentence for the user.
      System.debug(LoggingLevel.ERROR, e.getTypeName() + ': ' + e.getMessage() + '\n' + e.getStackTraceString());
      String message = (e instanceof QueryException || e instanceof NoAccessException)
          ? 'You do not have access to some of the data this board needs.'
          : 'The referral board could not be loaded. Try again, and tell an admin if it keeps failing.';
      AuraHandledException ex = new AuraHandledException(message);
      ex.setMessage(message); // without this, tests and some clients see "Script-thrown exception"
      return ex;
  }

Error handling

An uncaught exception reaches the browser as an unhelpful “An internal server error has occurred” with a stack trace in the console. AuraHandledException is the way to hand the component a message it can show. Three rules keep it honest:

  1. Catch broadly, throw narrowly. The catch (Exception e) is at the edge of the controller, where nothing above it can do better.
  2. Never put internals in the message. The user gets a sentence; the debug log gets the type, message and stack.
  3. Call setMessage. The constructor message is not what getMessage() returns on the server, which matters for the unit test on the Tests page.

The component

The wire reloads whenever maxRows changes, and the same wire result is kept so the component can refresh it by hand after a write. refreshApex re-runs the wired method and updates the cache, without re-rendering the whole page.

Illustrative: rebuilt for this site, not client codereferralBoard.js
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getBoard from '@salesforce/apex/ReferralBoardController.getBoard';
import acknowledge from '@salesforce/apex/ReferralBoardController.acknowledge';

const reduceError = (e) => e?.body?.message ?? e?.message ?? 'Something went wrong.';

export default class ReferralBoard extends LightningElement {
  @api maxRows = 25;
  board;
  error;
  boardResult; // the provisioned value refreshApex needs

  @wire(getBoard, { maxRows: '$maxRows' })
  loadBoard(result) {
      this.boardResult = result;
      const { data, error } = result;
      if (data) {
          this.board = data;
          this.error = undefined;
      } else if (error) {
          this.board = undefined;
          this.error = reduceError(error);
      }
  }

  get isLoading() { return !this.board && !this.error; }
  get hasCards() { return this.board?.cards?.length > 0; }
  get summary() {
      return this.board ? this.board.openCount + ' open, ' + this.board.urgentCount + ' urgent' : '';
  }
  get cards() {
      return (this.board?.cards ?? []).map((c) => ({
          ...c,
          canAcknowledge: c.status === 'New' && c.canEdit,
          badgeClass: c.isUrgent ? 'slds-badge slds-theme_error' : 'slds-badge'
      }));
  }

  async handleAcknowledge(event) {
      try {
          await acknowledge({ referralId: event.target.dataset.id });
          await refreshApex(this.boardResult);
          this.toast('Referral triaged', undefined, 'success');
      } catch (e) {
          this.toast('Could not triage the referral', reduceError(e), 'error');
      }
  }

  toast(title, message, variant) {
      this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
  }
}
Illustrative: rebuilt for this site, not client codereferralBoard.html
<template>
  <lightning-card title="My open referrals" icon-name="standard:approval">
      <p slot="actions" class="slds-text-body_small">{summary}</p>

      <div class="slds-p-horizontal_medium">
          <template lwc:if={isLoading}>
              <lightning-spinner alternative-text="Loading referrals" size="small"></lightning-spinner>
          </template>
          <template lwc:elseif={error}>
              <p class="slds-text-color_error" role="alert">{error}</p>
          </template>
          <template lwc:elseif={hasCards}>
              <ul class="slds-has-dividers_bottom-space">
                  <template for:each={cards} for:item="card">
                      <li key={card.recordId} class="slds-item slds-grid slds-grid_align-spread">
                          <div>
                              <p class="slds-text-heading_small">{card.name}: {card.patientName}</p>
                              <p class="slds-text-color_weak">{card.clinicName}, {card.daysSinceRouted} days ago</p>
                              <p lwc:if={card.latestNote}>{card.latestNote}</p>
                          </div>
                          <div>
                              <span class={card.badgeClass}>{card.priority}</span>
                              <lightning-button lwc:if={card.canAcknowledge} label="Triage" data-id={card.recordId}
                                  onclick={handleAcknowledge}></lightning-button>
                          </div>
                      </li>
                  </template>
              </ul>
          </template>
          <template lwc:else>
              <p>No open referrals. Nothing is waiting for you.</p>
          </template>
      </div>
  </lightning-card>
</template>

Notes on the component:

  • this.board is undefined while loading, and a template expression such as board.openCount would throw on it, so the header reads from a getter (summary) that handles the empty state.
  • cards maps the DTOs into view models (a badge class, whether the Triage button shows). Presentation decisions stay in the component, and facts stay in the wrapper.
  • The wire stays declarative for reads; the imperative call is only for the write, followed by refreshApex. That is the usual split.
  • Errors from Apex arrive as error.body.message, which is exactly the AuraHandledException message set above.

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

App Launcher