8.2 Data Prefill Patterns, Context Passing & Save-for-Later
Key Takeaways
- Context passing into OmniScripts leverages reserved parameters such as ContextId, recordId, and URL query strings, seamlessly seeding the client-side data JSON tree upon initialization.
- Data prefill architectures utilize Data Mapper Turbo Extract for rapid single-object retrieval or Integration Procedures for complex, multi-object PSS data aggregation and server-side payload trimming.
- The Save-for-Later framework preserves in-progress constituent intake sessions by serializing the active JSON state and step pointer into OmniProcessSavedInstance records.
- Security governance for Save-for-Later differentiates authenticated portal users (direct profile resume) from unauthenticated guest users, requiring multi-factor verification challenges and strict timeout expiration policies to prevent PII exposure.
- Custom Lightning Web Components (LWCs) extending OmniscriptBaseMixin can be embedded within OmniScript steps, enabling specialized capabilities like GIS mapping or biometric capture while maintaining bi-directional JSON synchronization.
8.2 Data Prefill Patterns, Context Passing & Save-for-Later
Exam Focus: Enterprise public sector intake processes must balance ease of constituent access with strict data privacy and security. AP-222 tests candidates on context passing mechanics (
ContextId, URL parameters), high-performance data prefill architectures (Data Mapper Turbo Extract vs. Integration Procedures), the Save-for-Later state preservation framework across authenticated and guest constituent personas, and the seamless integration of custom Lightning Web Components (LWCs) within OmniScript steps.
Context Passing: Seeding the OmniScript Runtime Environment
When a constituent or agency caseworker launches an OmniScript, the workflow rarely starts in complete isolation. The script must know who is applying, what facility is being evaluated, or which prior license is being renewed. OmniStudio establishes this contextual baseline through automated context passing mechanics.
The Reserved ContextId Parameter
The cornerstone of OmniScript context initialization is the reserved parameter ContextId. When an OmniScript initializes, it automatically scans its execution environment for this key and places its value at the root of the Data JSON:
- Lightning Record Page Context: When an OmniScript is placed on a standard Lightning Record Page (e.g., inside the Public Sector Service Console on a
Contact,Account, orBusinessLicenseApplicationpage layout), the page runtime automatically injects the active record's 18-character ID intoContextId(orrecordId). - URL Query Parameters: When an OmniScript is invoked from an Experience Cloud portal link, an email button, or an external portal redirect, parameters passed via query strings are parsed into the Data JSON automatically. For example, navigating to
/intake?ContextId=001xx000003DFA&programType=ChildCare&jurisdiction=NorthDistrictimmediately seeds the root JSON tree with:
{
"ContextId": "001xx000003DFA",
"programType": "ChildCare",
"jurisdiction": "NorthDistrict"
}
Parameter Merging and Downstream Propagation
Once seeded at the root of the Data JSON, context variables can be referenced anywhere throughout the OmniScript using standard merge field syntax (%ContextId% or %programType%). They can be passed directly as input parameters into Integration Procedures, evaluated in conditional view logic, or used to filter database queries during data prefill.
Data Prefill Architectures: Turbo Extract vs. Integration Procedure
Government agencies strive to adhere to the statutory "Tell Us Once" principle: if a citizen or registered business has already provided verified demographic, contact, or legal information to the state, the intake portal should prefill those details automatically rather than forcing repetitive data re-entry. Prefilling accelerates application completion, reduces typographical errors, and improves constituent trust.
In Public Sector Solutions, architects select between two primary prefill patterns based on architectural complexity:
+-----------------------------------------------------------------------------------+
| Prefill Architectural Decision Matrix |
+-----------------------------------------------------------------------------------+
| Pattern A: Data Mapper Turbo Extract |
| • Single-object extraction (e.g., Account or Contact via ContextId) |
| • High-speed, low CPU overhead, zero payload transformation |
| • Best for simple intake prefilling on a single entity |
+-----------------------------------------------------------------------------------+
| Pattern B: Integration Procedure on Step Initialization (Recommended Standard) |
| • Multi-object relational extraction (Person Account + ACR + Prior Licenses) |
| • Server-side payload trimming (stripping internal IDs, masking PII) |
| • Integration with external state databases via Named Credentials |
| • Caching support (Org/Session Cache) to protect database governor limits |
+-----------------------------------------------------------------------------------+
Pattern A: Data Mapper Turbo Extract (DataRaptor Turbo Extract)
A Data Mapper Turbo Extract is a specialized, high-performance extraction engine designed to retrieve fields from a single Salesforce object.
- Execution Mechanics: It executes an optimized SOQL query directly against the target object using
ContextIdas the filter (e.g.,Id = %ContextId%). - When to Use: When the prefill requirement is strictly limited to reading basic fields from a single record (e.g., retrieving
FirstName,LastName,Phone, andEmailfrom aContactrecord). - Limitations: Cannot perform multi-object joins, cannot reshape JSON hierarchies, and cannot invoke external web services.
Pattern B: Integration Procedure on Initialization [Recommended Enterprise Pattern]
In enterprise public sector implementations, prefilling rarely involves a single record. An applicant renewing an occupational license requires extracting their PersonAccount master record, active BusinessLicense records, pending inspection Visit dates, and fee exemption flags.
Architects place an Integration Procedure Action at the very beginning of the OmniScript (prior to the first user-facing Step):1. Multi-Source Aggregation: The IP executes multiple Data Mapper Extracts, joining data across Account, Contact, IndividualApplication, and standard PSS authorization tables.
2. External API Hydration: If statutory data resides in an external legacy database (such as a state department of revenue tax clearance system), the IP makes an outbound HTTP call via Named Credentials to retrieve clearance status in real time.
3. Server-Side Payload Trimming & Security: The IP uses Data Mapper Transforms to filter out internal system flags, audit fields, and sensitive unmasked PII before the payload is delivered to the constituent's browser.
4. Seamless Step Binding: The trimmed JSON is injected directly into the OmniScript Data JSON, where input elements automatically display the prefilled values by matching element names to JSON keys.
Save-for-Later Architecture & State Preservation
Comprehensive public sector applications—such as applying for a commercial hazardous waste permit, filing a complex civil rights complaint, or submitting foster parent eligibility packets—can take hours or days to complete. Applicants must gather financial statements, obtain notarized affidavits, and inspect physical facility measurements. Forcing constituents to complete such forms in a single browser session results in catastrophic abandonment rates.
OmniScript provides an enterprise-grade Save-for-Later framework that serializes the constituent's exact form state, allowing them to exit and resume the application seamlessly across different devices and sessions.
State Serialization and the Storage Model
When an applicant clicks the "Save for Later" button on any OmniScript step:
- In-Flight State Capture: The OmniScript client runtime captures the entire active Data JSON tree, the current step pointer (e.g., Step 3 of 6), and all uploaded temporary document attachment IDs.
- Database Serialization: The state is transmitted to the Salesforce server and serialized into an
OmniProcessSavedInstancerecord (orvlocity_ins__OmniScriptInstance__cin legacy managed package instances). - Instance Attributes: The saved instance record captures key metadata: the associated
OmniProcessId, the applicant'sUserId(if authenticated), the resume token, creation and modification timestamps, and expiration deadlines.
Configuring the Save-for-Later User Experience
Administrators configure Save-for-Later within the OmniScript Setup properties:
- Enable Save for Later: Toggles the visibility of the "Save for Later" link on designated steps.
- Customizable Prompt & Confirmation: Displays a modal dialog prompting the applicant to confirm saving. Administrators can customize modal headers, instructional guidance, and button labels.
- Save-for-Later Email Integration: Automatically invokes an email template delivering a personalized message containing a secure, unique Resume URL.
Security Governance & Timeout Policies: Authenticated vs. Guest Users
The implementation architecture for Save-for-Later differs fundamentally depending on whether the constituent is logged into an authenticated portal or interacting as an unauthenticated guest citizen.
| Architectural Dimension | Authenticated Portal Constituents | Unauthenticated Guest Citizens |
|---|---|---|
| User Identity | Known portal user (User linked to PersonAccount) | Salesforce Guest User Site Profile |
| Resume Mechanism | Direct portal dashboard ("My Saved Applications" FlexCard) or authenticated email link | Encrypted Resume URL with mandatory Identity Challenge Verification |
| PII Exposure Risk | Low; access governed by Salesforce Login & Sharing Rules | High; public URL interception could expose confidential citizen data |
| Data Ownership | Saved instance record is owned by or shared with the authenticated user | Saved instance record is owned by an internal automated administrative user |
| Mandatory Security Layer | Standard Multi-Factor Authentication (MFA) on portal login | Identity Verification Challenge (PIN, SMS/Email One-Time Passcode, SSN/EIN validation) |
Unauthenticated Guest User Security Architecture
Allowing anonymous guest users to save and resume forms introduces severe security vulnerabilities if not properly architected. If a guest user's resume URL (which contains the saved instance ID) is shared, intercepted, or exposed in public browsing histories, an unauthorized individual could open the URL and view the applicant's private personal data, tax filings, or medical disclosures.
To satisfy public sector security audits, architects must implement Guest User Identity Challenges:
- Token Generation: When a guest user saves, the system generates a secure, randomized resume token.
- Identity Challenge Gate: When the resume URL is accessed, the OmniScript does not immediately populate the saved Data JSON into the browser. Instead, it renders an Identity Verification Gate.
- Multi-Factor / Identity Challenge: The constituent must prove ownership by providing matching secondary identifiers (such as the last 4 digits of their SSN/Tax ID, date of birth, or a one-time passcode sent via SMS/Email) that match the encrypted data on file.
- Hydration Upon Success: Only after the verification check passes does the system deserialize the saved JSON tree and return the user to their exact in-progress step.
Timeout and Data Retention Governance
Public sector compliance frameworks (e.g., CJIS, HIPAA, state public records retention laws) prohibit storing unsubmitted constituent data indefinitely.
- Configurable Expiration: OmniProcessSavedInstance records feature an expiration duration (e.g., 30 calendar days).
- Automated Lifecycle Purging: Scheduled batch Apex jobs or automated Flows regularly query expired saved instances, purge the temporary JSON payloads, delete associated temporary file attachments from
ContentDocument, and notify the applicant that their expired draft has been archived.
Embedding Custom Lightning Web Components (LWC) in OmniScripts
While OmniScript provides an extensive palette of standard inputs, complex public sector processes often demand specialized, highly custom user interfaces that exceed standard HTML inputs.
Common Public Sector Custom LWC Scenarios:
- Interactive GIS Spatial Mapping: Allowing an applicant to click a municipal parcel map to automatically capture cadastral zoning boundaries and GPS coordinates for a building variance.
- Biometric & Canvas Signature Capture: Capturing high-fidelity digital pen signatures with statutory legal audit attestations.
- Interactive Floor Plan Annotations: Enabling restaurant owners to drop inspection pins indicating food prep, refrigeration, and fire extinguisher stations.
- Camera ID Verification: Capturing live smartphone camera feeds to perform real-time optical character recognition (OCR) and facial match verification.
Architectural Integration: The OmniscriptBaseMixin Framework
To embed a custom LWC seamlessly into an OmniScript step, the custom component must extend the official OmniscriptBaseMixin component library provided by OmniStudio.
import { LightningElement, api } from 'lwc';
import { OmniscriptBaseMixin } from 'omnistudio/omniscriptBaseMixin';
export default class PublicSectorGisMap extends OmniscriptBaseMixin(LightningElement) {
@api parcelData;
handleParcelSelected(event) {
const selectedParcel = event.detail;
// 1. Mutate the OmniScript Data JSON Tree in real time
this.omniUpdateDataJson({
"ZoningDetails": {
"ParcelId": selectedParcel.id,
"ZoningClassification": selectedParcel.zone,
"CadastralCoordinates": selectedParcel.coordinates
}
});
// 2. Apply server responses if necessary
this.omniApplyCallResp({ "isParcelVerified": true });
// 3. Programmatically advance step if desired
// this.omniNextStep();
}
}
Bi-Directional Data Synchronization Lifecycle
- Reading Inbound Data: The embedded LWC accesses incoming data from the OmniScript through the reactive property
this.omniJsonData. Any upstream data entered by the constituent in earlier steps is instantly available to the custom component. - Writing Outbound Data: When the constituent interacts with the custom component (e.g., selects a property parcel on the map), the component calls
this.omniUpdateDataJson(data). This method merges the new data directly into the specified path in the OmniScript Data JSON. - Step Validation Hook: Custom LWCs can participate in OmniScript step validation by exposing standard validation methods (
checkValidity()). If a constituent fails to select a valid parcel on the GIS map, the LWC signals an invalid state, preventing the OmniScript from advancing when the user clicks "Next".
Architectural Trade-offs & Implementation Decision Matrix
| Architecture Option | Strengths | Limitations | Public Sector Recommendation |
|---|---|---|---|
| Standard OmniScript Elements | 100% declarative, zero code maintenance, automatic WCAG 2.1 AA compliance, upgrades seamlessly | Limited to standard UI controls (text, dropdowns, tables, standard file uploads) | Default choice: Use for 90%+ of standard public intake forms |
| Custom LWC embedded in OmniScript | Combines guided workflow, Save-for-Later, and IP integration with limitless bespoke UI capabilities | Requires custom JavaScript development, ongoing maintenance, and manual accessibility testing | Targeted use: Reserve for specialized interactions (GIS maps, signature pads, live camera feeds) |
| External Standalone Web App (e.g., React on Heroku) | Complete control over external styling and third-party JavaScript libraries | Complete disconnect from standard PSS data models, requires building custom authentication, state saving, and APIs | Anti-pattern: Avoid unless strict non-Salesforce statutory constraints dictate external hosting |
💡 Real-World AP-222 Exam Scenarios & Case Analysis
Scenario 1: Multi-Step Public Assistance with Guest Save-for-Later & MFA
A state Department of Social Services launches a food assistance (SNAP) intake portal. Because many vulnerable citizens apply using public library terminals or shared mobile devices, applicants must be permitted to start applications as unauthenticated guest users, save their progress, and resume later. Agency security officers raise critical concerns regarding public library terminal histories exposing household income and personal data.
How must the Lead Architect configure Save-for-Later to satisfy both accessibility and security?
- Enable Save for Later in the OmniScript properties and configure an automated email notification containing a secured resume token link.
- Configure an Identity Challenge Gate on the resume step: when the resume link is clicked, the OmniScript displays a challenge screen requiring the applicant to enter their last 4 digits of SSN and a 6-digit one-time passcode (OTP) delivered to their verified email/mobile phone.
- Store the temporary state in
OmniProcessSavedInstancewith a 14-day expiration policy, after which an automated batch job deletes unsubmitted draft records and associated file attachments to protect constituent privacy.
Scenario 2: Municipal Zoning Variance Application with Custom GIS Mapping
A city planning department requires an online zoning variance application. Applicants must input their facility address, view an interactive map showing municipal flood zones and zoning overlays, select their parcel boundary, and confirm setback distances. The city's GIS spatial mapping system operates on an external Esri ArcGIS platform.
What is the recommended OmniStudio architecture to satisfy this requirement?
- Build the guided intake journey using OmniScript to handle applicant identity, document uploads, and fee calculations.
- Embed a Custom Lightning Web Component within the property location step that extends
OmniscriptBaseMixin. - The custom LWC connects to the municipal Esri ArcGIS REST API using Named Credentials, renders the interactive spatial map, and allows the user to click their parcel.
- When the parcel is clicked, the LWC invokes
this.omniUpdateDataJson()to write the selectedParcelNumber,ZoningCode, andFloodZoneRiskdirectly into the OmniScript Data JSON tree, enabling downstream steps to conditionally require flood mitigation affidavits.
A county health department needs to prefill an existing constituent's contact information, active business licenses, and open inspection records into an OmniScript renewal application upon initialization. Which architectural prefill pattern should the consultant recommend?
An agency is deploying a complex 45-minute environmental permit application on a public Experience Cloud portal accessible to unauthenticated guest citizens. The agency requires Save-for-Later functionality. Which security governance measure is mandatory to prevent unauthorized access to constituent PII when an application is resumed?
A municipal developer is building a custom Lightning Web Component (LWC) that allows constituents to interact with a GIS map, select a property parcel, and pass the selected parcel data back into the parent OmniScript form. Which technical implementation is required?