Data loaders, creating, managing and how they work

Loaders define what supporting records an app fetches: contacts, jobs, sites, certificates, working patterns and so on. Each loader is a small JSON definition of a query. The query runs entirely in Apex, and the browser only ever receives the results.

Where loaders live

Loaders live on the app definition record they belong to, in its b3s__Loaders__c field: a JSON array of loader definitions.

Definition record Used by
b3s__Scheduling_Context_Provider__mdt the Scheduler (one provider per context object or sharing group)
b3s__Component_Configuration__mdt all component apps (Clock, Terminal, Timesheeting, Client Shift Manager, Vendor Portal)
[
    {
        "name": "sites",
        "objectName": "b3s__Site__c",
        "fieldToLoad": ["Name", "b3s__Account__c"],
        "filterRecordsBy": "b3s__Account__c = :contextId"
    },
    {
        "name": "jobs",
        "objectName": "b3s__Job__c",
        "fieldToLoad": ["Name"],
        "filterRecordsBy": "b3s__Account__c = :contextId"
    }
]

Every entry needs a unique name. A missing name, a duplicate name, or anything other than an array of objects fails the app's boot call with a Malformed b3s__Loaders__c error.

Each definition key must resolve to exactly one record: one Scheduling Context Provider per b3s__Object_Name__c, one Component Configuration per b3s__Type__c. Two records sharing a key fail the boot call (and every loader call) with Duplicate <object> records for <key field> [<key>]: <DeveloperNames>. Delete or re-key one of them.

Keeping loaders on the definition record means one record is the whole app configuration: deploying, cloning or retiring an app touches one record, and the loaders always come from the same record as the definition.

Legacy loader records

The older per-record loader types still work and are merged in at boot:

CMT Used by How records are matched to the app
b3s__Scheduling_Loader__mdt the Scheduler b3s__Object_Name__c must equal the context object API name (for example Account) or the sharing group name the scheduler was opened with.
b3s__Component_Loader__mdt component apps linked to a parent b3s__Component_Configuration__mdt.

If a legacy record and an entry in b3s__Loaders__c share the same name, the b3s__Loaders__c entry wins and the record is ignored.

Legacy records are deprecated. When an app boots with any legacy loader record, it logs a browser console warning naming the records and pointing here. There is no automatic migration on upgrade. To migrate:

  1. Copy each record's b3s__JSON__c object into the b3s__Loaders__c array of its provider or configuration (keep the name).
  2. Deploy the definition record and reload the app. Embedded entries take over immediately because they win on name.
  3. Delete the legacy records. The console warning stops.

Both forms share the same JSON contract.

JSON only, the legacy JavaScript form is gone

Loaders use JSON, either in the definition record's b3s__Loaders__c array or in a legacy loader record's b3s__JSON__c field. The old b3s__Javascript_Code__c snippet form is no longer read at all. Its filterRecordsBy functions, filteringItems, {0} positional tags and closure variables (contextRecordId, events) do not exist anymore.

A legacy loader record with an empty or invalid b3s__JSON__c is a boot error. The app's metadata call fails with Loader <DeveloperName> has no b3s__JSON__c setup (or a parse error). Migrate or delete every legacy record before upgrading.

How a loader executes

The key design point is that the query definition never reaches the browser.

  1. Boot: the app calls DataLoadingService.getSupportingMetadata. For each loader the client receives only a descriptor: developerName, name, label, objectName, groupRecordsBy, plus source (definition for b3s__Loaders__c, record for a legacy record) and, for scheduler loaders, the definitionKey they were served under. The filterRecordsBy, fieldToLoad and apexFilter values stay server side.
  2. Load: for each descriptor the client calls DataLoadingService.getLoaderData with the loader's name, its source as loaderSource, and definitionKey, plus its context (record id, user, calendar window). Apex re-reads the JSON (from the definition record resolved by app type and definition key, or from the legacy record by DeveloperName), merges the placeholders, and runs the query.
  3. Stream: results come back in Id cursored pages (see Batching below) and land in a client side loader state, { records: [...], grouped: { key: [...] } }, keyed by the loader's name. App configuration references loaders by that name.

Because the definition is read server side, the client cannot alter the query. It can only supply the context values, and even those are validated and escaped in Apex.

Access level. The permissions a loader runs with are derived from its owning app, a server side fact:

Practical consequence: in the scheduler a loader returns only records the running user can see. If two users see different row counts, check sharing before checking the loader.

JSON reference

{
    "name": "contacts",
    "label": "Workers",
    "objectName": "Contact",
    "fieldToLoad": ["Name", "Email", "MailingLatitude", "MailingLongitude"],
    "groupRecordsBy": "Id",
    "filterRecordsBy": "Id IN (SELECT b3s__Contact__c FROM b3s__Group_Assignment__c WHERE b3s__Group__c = :contextId)"
}
Property Required Description
name yes Unique loader name within the definition. This is what app configurations and components reference, and what the server looks an embedded loader up by. (For a legacy record the server uses the CMT DeveloperName.)
objectName yes API name of the object to query.
filterRecordsBy yes* SOQL WHERE clause string, or an array of strings. Each array entry runs as a separate query, and results are merged and de-duplicated by Id. *Optional when apexFilter is set.
fieldToLoad no Array of field API names or relationship paths to retrieve. Id is always included. Every entry is identifier validated server side.
groupRecordsBy no Field to group the results by on the client (the grouped state). Combine fields with * for a composite key, for example b3s__Account__c*b3s__Site__c.
label no Friendly name used in error messages and UI.
apexFilter no Name of an Apex FilterPlugin class, for example "b3s.GroupShiftLoader". See Apex filters.

Notes:

Merge placeholders

Use these inside filterRecordsBy. They are resolved in Apex, with values quoted and SOQL escaped automatically. Never add quotes yourself (Id = :contactUserId, not Id = ':contactUserId').

Placeholder Resolves to
:contextId Id of the record the app was opened on (Account, Job, sharing Group).
:contactUserId The acting contact's Id. For portal sessions this is always the signed-in contact.
:userId Alias of :contactUserId.
:contextRecord.<FieldApiName> A field value from the context record, resolved server side and escaped by type (for example :contextRecord.b3s__Region__c). Relationship paths are supported.
:contextUser.<FieldApiName> A field value from the acting contact's record.
:accountIds A quoted Id list of every account the acting contact acts for. Write IN :accountIds. Without an access profile this is the contact's own Account; with one it is their Account Membership accounts.
:accountIds(<checkbox>) The same list limited to accounts whose User Profile ticks that checkbox API name, for example IN :accountIds(b3s__Tab_Workers__c).
:sbuIds A quoted Id list of the running user's business units (their User SBU Assignments). Write b3s__SBU__c IN :sbuIds. Unrestricted when SBU mode is off or the user has no assignment: every active SBU plus blank ((null,'id1',...)), so the clause is always safe.
:userSbuId The running user's primary SBU as a quoted Id, or '' when none.
:contextStart Start of the date window being loaded (the calendar's visible range or the app's fetch window), as a SOQL datetime.
:contextEnd End of that window.
:contextStart-Nd / :contextStart+Nd The window start shifted by N days, as a SOQL datetime (for example :contextStart-7d is 7 days before the window). The same forms work on :contextEnd. Use these to load records around, not just inside, the visible window.
:contextStartDate / :contextEndDate The window start or end as a SOQL date (YYYY-MM-DD, GMT), for Date fields such as a placement's b3s__Start__c / b3s__End__c. The GMT date can make the window up to one day wider, never narrower.
:contextDate The single context date some component apps send (YYYY-MM-DD). Validated against a strict date charset.
:now The server time of the request, as a GMT SOQL datetime. For Datetime fields only (for example b3s__Absolute_End_Time__c >= :now); on Date fields use TODAY or LAST_N_DAYS:n.
:now-Nd / :now+Nd The request time shifted by N days, as a SOQL datetime (for example :now-90d).

Resolution rules worth knowing:

Schedulable clause sets

Schedulable records (shifts, expenses and so on, loaded by DataLoadingService.loadRecords) use the same placeholders in their selectionClause. A schedulable can declare other clause sets beside it, and the app picks one by sending clauseField. Only these names are accepted; anything else fails with Invalid clauseField:

clauseField Used by Date window
selectionClause (default) Every app Applied
matchSelectionClause Clock open shift marketplace Applied
requestSelectionClause Client Shift Manager VMS tabs (shift), and the base clause of the server-paged Requests (shift, bookingRequest) and Vendor Portal Invites (invite) lists Applied by loadRecords. Not applied by a server-paged list: its scope clauses own the dates
outstandingClause Timesheet Approval Outstanding list (earlier timesheets still awaiting a decision) Not applied: the clause carries its own date bound, for example b3s__Absolute_Start_Time__c < :contextStart+1d

The date window is built on dateFilterFieldPath when the schedulable sets it, else absoluteStartFieldPath, else startFieldPath. With isFieldPathDateType: true the window edges are emitted as date literals, so a Date field such as b3s__Site_Work_Date__c can anchor the period while the datetime paths still drive the display.

Server-paged lists

A loader returns every matching record, in Id order. For a list the user pages through, sorted and counted (the Client Shift Manager Requests tab, the Vendor Portal Invites tab), declare it under the definition root key lists instead. DataLoadingService listRecords then sorts, scopes, searches, counts and pages it on the server, and the browser only receives the current page. The request and response are in the Apex API reference.

"lists": {
    "requests": {
        "pageSize": 12,
        "sources": [
            {
                "name": "shift",
                "type": "shift",
                "clauseField": "requestSelectionClause",
                "sort": {
                    "priority": "b3s__VMS_Action_Priority__c",
                    "start": "b3s__Absolute_Start_Time__c",
                    "end": "b3s__Absolute_End_Time__c"
                },
                "searchFieldPaths": ["Name", "b3s__Work_Job__r.Name", "b3s__Work_Site__r.Name", "b3s__PO_Number__c"]
            }
        ],
        "scopes": [
            {
                "name": "active",
                "sort": [{ "key": "priority" }, { "key": "start" }],
                "clauses": { "shift": "b3s__VMS_Stage__c IN ('New','Broadcasting','Proposals')" }
            },
            {
                "name": "past",
                "period": true,
                "sort": [{ "key": "end", "descending": true }],
                "clauses": {
                    "shift": "b3s__Absolute_End_Time__c < :now AND b3s__Absolute_End_Time__c >= :contextStart AND b3s__Absolute_End_Time__c <= :contextEnd"
                }
            }
        ],
        "related": [
            { "loader": "vmsInvites", "keys": [{ "field": "b3s__Shift__c" }] }
        ]
    }
}
Key Description
lists.<key> One list. The app names the key it reads (requests on the Client Shift Manager, invites on the Vendor Portal).
pageSize Rows per page, 1 to 200. Default 12.
sources[] The record sets merged into one list. Order matters: it breaks ties.
sources[].name Unique name. Scopes and the app's source filter refer to it.
sources[].type The schedulable the rows come from. Its objectType is the object, its field paths are the fields loaded, and its apexFilter (or matchApexFilter with matchSelectionClause) applies.
sources[].clauseField Which clause set of the schedulable is the base filter: selectionClause (default), matchSelectionClause, requestSelectionClause or outstandingClause. No date window is added.
sources[].clause Optional extra filter for this source, for example b3s__Shift__c != null to split one object into two sources.
sources[].sort Map of sort key to field path. Every key a scope sorts by must be mapped on every source the scope uses.
sources[].searchFieldPaths Fields the search box matches (SOQL LIKE '%term%', OR-ed). A source with no search fields is left out of the list while a search is active.
scopes[] The options of the scope select. The app shows them in this order.
scopes[].name Unique name, also the translation key suffix.
scopes[].clauses Map of source name to clause. A source missing from the map is not part of the scope. An empty string means no extra filter.
scopes[].sort Ordered [{ "key", "descending"? }]. Nulls sort last. Ties fall back to the source order, then Id.
scopes[].period true makes the scope date driven: the app shows a date control and sends :contextStart / :contextEnd (also usable as :contextStartDate / :contextEndDate). The scope gets no count.
related[] Loaders whose rows belong to the listed records (invites, proposals, chat messages, requirements).
related[].loader The name of a loader in the same definition's b3s__Loaders__c. It must not use apexFilter, and its clauses must not contain LIMIT or ORDER BY.
related[].keys[] { "field", "path"? }: the loader's rows where field is in the path values (default Id) of the listed records. Several keys are OR-ed.

How a page is built:

  1. Each source's filter is the base clause, then the plugin Ids, then the source clause, then the scope clause, then the search, all joined with AND. Each part is wrapped in brackets unless it holds a semi-join (IN (SELECT ...)), which SOQL does not allow inside brackets.
  2. The server reads the Id and sort fields of every source, merges them in Apex and cuts out the page.
  3. It loads the full fields for the page's rows, plus any rows the app pins (open consoles, at most 20). Pinned rows must still match the source's base clause and clause.
  4. It loads the related loaders for those rows, each loader clause ANDed with the keys.

Rules and limits:

Apex filters

When a WHERE clause cannot express the filter (typically multi-level semi-joins, which SOQL rejects), a loader or an app definition schedulable can name an Apex class instead:

{
    "name": "groupPatterns",
    "objectName": "b3s__Working_Pattern__c",
    "fieldToLoad": ["Name", "b3s__Start__c", "b3s__End__c"],
    "apexFilter": "b3s.GroupWorkingPatternLoader"
}

The class implements the packaged global interface FilterPlugin and returns the Set<Id> of records that pass. The server ANDs Id IN :ids into the query as a bind variable (no statement length limit, pagination unchanged). Full contract, context map, limits and testing guidance are in Apex filters.

Batching and large data sets

Loaders are built to return very large sets (100k or more records):

Operational notes

Shipped scheduler loaders

Beyond the contact, job, site, location, working pattern, certificate and suitability loaders, the scheduler ships:

Loader name Object Used by
rateCards b3s__Rate_Card__c the Rate card compliance rule
rateCardItems b3s__Rate_Card_Item__c the Rate card compliance rule

Each is declared in the b3s__Loaders__c of every sample scheduling context provider (WFM_Account, WFM_Contact, WFM_Job, WFM_Group). The sample component configurations (WFM_Clock_In_Out_Config, WFM_Client_Shift_Manager, WFM_Timesheet_Approval, WFM_Timesheet_Submission, WFM_Vendor_Portal, WFM_Candidate_Availability) carry their loaders the same way. No legacy loader records ship.