Sf flow
Creates and validates Salesforce Flows with 110-point scoring. TRIGGER when: user builds or edits record-triggered, screen, autolaunched, or scheduled flows, or touches .flow-meta.xml files. DO NOT TRIGGER when: Apex automation (use sf-apex), process builder migration questions only, or non-Flow declarative config (use sf-metadata).
By- name:
- sf-flow
- description:
- Creates and validates Salesforce Flows with 110-point scoring. TRIGGER when: user builds or edits record-triggered, screen, autolaunched, or scheduled flows, or touches .flow-meta.xml files. DO NOT TRIGGER when: Apex automation (use sf-apex), process builder migration questions only, or non-Flow declarative config (use sf-metadata).
sf-flow: Salesforce Flow Creation and Validation
Use this skill when the user needs Flow design or Flow XML work: record-triggered, screen, autolaunched, scheduled, or platform-event Flows, including validation, architecture choices, and safe deployment sequencing.
When This Skill Owns the Task
Use sf-flow when the work involves:
.flow-meta.xmlfiles- Flow Builder architecture and XML generation
- record-triggered, screen, scheduled, autolaunched, or platform-event flows
- Flow-specific bulk safety, fault paths, and subflow orchestration
Delegate elsewhere when the user is:
- writing Apex-first automation → sf-apex
- creating objects / fields first → sf-metadata
- deploying metadata → sf-deploy
- seeding post-deploy test data → sf-data
Required Context to Gather First
Ask for or infer:
- flow type
- trigger object / entry conditions
- core business goal
- whether this is new, refactor, or repair
- target org alias if deployment or validation is needed
- whether related objects / fields already exist
Recommended Workflow
1. Choose the right automation tool
Before building, confirm Flow is the right answer rather than:
- formula field
- validation rule
- roll-up summary
- Apex
2. Choose the right Flow type
| Need | Default flow type |
|---|---|
| same-record update before save | before-save record-triggered |
| related-record work / emails / callouts | after-save record-triggered |
| guided UI | screen flow |
| reusable background logic | autolaunched / subflow |
| scheduled processing | scheduled flow |
| event-driven declarative response | platform-event flow |
| AI-evaluated routing (sentiment, intent, tone) | autolaunched with AI Decision element |
3. Start from a template
Prefer the provided assets:
assets/record-triggered-before-save.xmlassets/record-triggered-after-save.xmlassets/screen-flow-template.xmlassets/autolaunched-flow-template.xmlassets/scheduled-flow-template.xmlassets/platform-event-flow-template.xmlassets/ai-decision-template.xmlassets/subflows/
4. Validate against Flow guardrails
Focus on:
- no DML in loops
- no Get Records inside loops
- proper fault paths
- correct trigger conditions
- safe subflow composition
- AI Decision elements not placed inside loops (credit cost per iteration)
- AI Decision prompts include merge field references for data context
5. Hand off deployment and testing
Use:
High-Signal Rules
Flow architecture
- before-save for same-record field updates
- after-save for related records, emails, and callouts
- do not loop over
$Record - use subflows when logic becomes wide or repetitive
Bulk safety
- no DML in loops
- no Get Records in loops
- test with 251+ records when bulk behavior matters
- prefer Transform when the job is shaping data, not per-record branching
Error handling
- every data-changing path should have fault handling
- avoid self-referencing fault connectors
- deploy Flows as Draft first when activation risk is non-trivial
Output Format
When finishing, report in this order:
- Flow type and goal
- Files created or updated
- Architecture choices
- Bulk/error-handling notes
- Deploy/testing next steps
Suggested shape:
Flow: <name>
Type: <flow type>
Files: <paths>
Design: <trigger choice, subflows, key decisions>
Risks: <bulk safety, fault paths, dependencies>
Next step: <dry-run deploy, activate, or test>
Flow Testing (CLI)
Run Flow tests from the command line without VS Code:
# Run all flow tests
sf flow run test --target-org <alias> --json
# Run tests for a specific flow
sf flow run test --class-names MyFlow --target-org <alias> --json
# Get results for an asynchronous run
sf flow get test --test-run-id <id> --target-org <alias> --json
Flow tests execute in the org and can take 1-5 minutes. sf flow run test returns a test run ID for asynchronous runs; use sf flow get test to retrieve results later. Always run with --json and use background execution for longer runs.
Cross-Skill Integration
| Need | Delegate to | Reason |
|---|---|---|
| create objects / fields first | sf-metadata | schema readiness |
| deploy / activate flow | sf-deploy | safe deployment sequence |
| create realistic bulk test data | sf-data | post-deploy verification |
| create Apex actions / invocables | sf-apex | imperative logic |
| embed LWC in a screen flow | sf-lwc | custom UI components |
| expose Flow to Agentforce | sf-ai-agentscript | agent action orchestration |
Reference Map
Start here
- references/flow-best-practices.md
- references/flow-quick-reference.md
- references/orchestration.md
- references/testing-guide.md
Design / orchestration
- references/subflow-library.md
- references/governance-checklist.md
- references/transform-vs-loop-guide.md
- references/orchestration-guide.md
- references/orchestration-parent-child.md
- references/orchestration-sequential.md
- references/orchestration-conditional.md
AI Decision
Screen / integration / troubleshooting
- references/form-building-guide.md
- references/integration-patterns.md
- references/lwc-integration-guide.md
- references/agentforce-flow-integration.md
- references/xml-gotchas.md
- references/testing-checklist.md
- references/wait-patterns.md
- assets/
Score Guide
| Score | Meaning |
|---|---|
| 88+ | production-ready Flow |
| 75–87 | good Flow with some review items |
| 60–74 | functional but needs stronger guardrails |
| < 60 | unsafe / incomplete for deployment |
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flows for Agentforce (sf-ai-agentscript)
When sf-ai-agentscript Requests a Flow
- sf-ai-agentscript will invoke sf-flow (this skill) to create Flows
- sf-flow creates the validated Flow XML
- sf-deploy handles deployment to org
- Action Definition registration required (see below)
- Only THEN can sf-ai-agentscript use
flow://FlowNametargets
Variable Name Matching
When creating Flows for Agentforce agents:
- Agent Script input/output names MUST match Flow variable API names exactly
- Use descriptive names (e.g.,
inp_AccountId,out_AccountName) - Mismatched names cause "Internal Error" during agent publish
Output Variable Naming for Agentforce
Use out_ prefix for output variables to distinguish them in Action Definition schema:
<variables>
<name>out_CaseSubject</name>
<dataType>String</dataType>
<isOutput>true</isOutput>
</variables>
<variables>
<name>out_CaseStatus</name>
<dataType>String</dataType>
<isOutput>true</isOutput>
</variables>
Formula Expression Limitations in Flows
| Function | Status | Alternative |
|---|---|---|
BLANKVALUE() |
Not in Flow | Use Decision element or IF() |
CASESAFEID() |
Not in Flow | ID variables handle this automatically |
ISNEW() / ISCHANGED() |
Not in Flow | Use $Record__Prior comparisons |
Action Definition Registration (REQUIRED)
CRITICAL: Creating a Flow is NOT sufficient for Agentforce. The Flow must be registered as an Action Definition.
Registration Workflow:
- Deploy Flow to target org via sf-deploy
- Navigate to Setup > Agentforce > Action Definitions
- Click "New Action", select "Flow" as target type
- Choose your deployed Flow from the list
- Map input/output variables — these become the action's schema
- Configure output-visibility flags intentionally:
filter_from_agent: GA hide-from-user flag when an output should not be rendered directly to the customeris_displayable: direct-display flag / alias;Falsehides direct displayis_used_by_planner: planner visibility flag when the output should influence routing or response synthesis- If a field is hidden but should still drive the response, make it planner-visible too
- Do not combine
filter_from_agentandis_used_by_planneron the same output field in Agent Script-driven actions
- Save the Action Definition
Flow Created → Deployed to Org → Action Definition Created → Agent Can Use
↑ ↑ ↑ ↑
sf-flow sf-deploy Setup > Agentforce @actions.MyAction
Why This Matters: The Action Definition is what exposes the Flow to the agent runtime. Without it, @actions.FlowName will fail with ValidationError: Tool target 'FlowName' is not an action definition.
Open this reference as its own page
AI Decision Element Guide
Overview
The AI Decision element ("Define with AI") lets AI evaluate flow data at runtime to determine which outcome path to follow. Instead of manually defining conditions (e.g., "Status equals Closed"), you write natural-language instructions and AI decides which outcome fires.
Introduced in API version 62.0 (Spring '25). Requires Einstein AI credits.
XML Structure
An AI Decision is a standard <decisions> element with <attributes> blocks of type LlmPrompt. There is no separate element type — the <attributes> block is the only difference from a manual decision.
Decision-level instructions
<decisions>
<name>Route_Case_Based_on_Sentiment</name>
<label>Route Case Based on Sentiment</label>
<attributes>
<type>LlmPrompt</type>
<value>Detect the sentiment on the case based on subject
"{!Get_Case.Subject}" and description
"{!Get_Case.Description}" as Negative, Positive,
Neutral, or Undetermined.</value>
</attributes>
<defaultConnector>
<targetReference>Handle_Default</targetReference>
</defaultConnector>
<defaultConnectorLabel>Not Negative</defaultConnectorLabel>
<rules>
...
</rules>
</decisions>
Outcome-level instructions
Each <rules> block (outcome) also gets an <attributes> block describing when AI should choose that path:
<rules>
<name>Negative</name>
<attributes>
<type>LlmPrompt</type>
<value>The customer's sentiment is Negative. The case
subject or description contains language indicating frustration,
anger, dissatisfaction, complaint, or urgency.</value>
</attributes>
<conditionLogic>and</conditionLogic>
<connector>
<targetReference>Assign_to_Senior_Support</targetReference>
</connector>
<label>Negative</label>
</rules>
Key structural notes
| Aspect | Detail |
|---|---|
| Element type | Standard <decisions> — no new XML element |
| AI marker | <attributes><type>LlmPrompt</type><value>...</value></attributes> |
| Decision instructions | <attributes> as a direct child of <decisions> |
| Outcome instructions | <attributes> as a direct child of each <rules> |
| Conditions | No <conditions> block needed; <conditionLogic>and</conditionLogic> is present but vestigial |
| Default outcome | No <attributes> block needed — it catches everything not matched |
| Merge fields | Use {!Element.Field} references in prompt text so AI has data context |
| XML escaping | " for quotes, ' for apostrophes inside <value> |
When to Use AI Decision vs Manual Decision
| Use AI Decision when | Use manual Decision when |
|---|---|
| Conditions are subjective (sentiment, intent, tone) | Conditions are objective (status = "Closed") |
| You need NLP-style evaluation of free-text fields | You're comparing picklist or numeric values |
| The routing logic would require many complex rules | A few simple conditions cover all cases |
| You want flexible, less predetermined outcomes | Deterministic behavior is required |
Writing Effective Instructions
Decision Instructions (element level)
- Describe the overall decision the AI is making
- Include merge field references (
{!Get_Case.Subject}) so AI has data - List all possible categories the AI should classify into
- Be specific about what data to evaluate
Good:
Detect the sentiment on the case based on subject "{!Get_Case.Subject}" and description "{!Get_Case.Description}" as Negative, Positive, Neutral, or Undetermined.
Bad:
Figure out the sentiment.
Outcome Instructions (rule level)
- Describe when this specific outcome applies
- Include concrete indicators or signals AI should look for
- Be mutually exclusive with other outcomes where possible
Good:
The customer's sentiment is Negative. The subject or description contains language indicating frustration, anger, dissatisfaction, complaint, or urgency.
Bad:
Negative sentiment.
Governance and Cost
- Each AI Decision evaluation consumes Einstein credits. Monitor usage in Setup > Digital Wallet.
- Avoid placing AI Decision elements inside loops — each iteration costs credits.
- AI Decision adds latency (LLM call) — not suitable for high-volume record-triggered flows.
- Best suited for autolaunched flows, screen flows, or low-volume triggers.
- Debug your automation to verify AI is routing to the correct outcome before activation.
Template
See assets/ai-decision-template.xml for a copy-paste starting point.
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Error Logging Pattern Example
Overview
This example demonstrates how to use the Sub_LogError reusable subflow to implement structured error logging in your flows. Structured error logging provides visibility into flow failures and accelerates debugging in production environments.
Prerequisites
- Deploy the Sub_LogError subflow from
assets/subflows/subflow-error-logger.xml - Create the Flow_Error_Log__c custom object with these fields:
Flow_Name__c(Text, 255)Record_Id__c(Text, 18)Error_Message__c(Long Text Area, 32,768)
Use Case
You have a Record-Triggered Flow on Account that updates related Contacts. If the Contact update fails, you want to log the error with context for troubleshooting.
Implementation Pattern
1. Main Flow with Fault Path
<recordUpdates>
<name>Update_Related_Contacts</name>
<label>Update Related Contacts</label>
<locationX>0</locationX>
<locationY>0</locationY>
<!-- Fault connector to error handler -->
<faultConnector>
<targetReference>Call_Error_Logger</targetReference>
</faultConnector>
<filters>
<field>AccountId</field>
<operator>EqualTo</operator>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</filters>
<inputAssignments>
<field>Industry</field>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
<object>Contact</object>
</recordUpdates>
2. Call Sub_LogError Subflow
<subflows>
<name>Call_Error_Logger</name>
<label>Call Error Logger</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>RTF_Account_UpdateContacts</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varErrorMessage</name>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</inputAssignments>
</subflows>
Benefits
✅ Structured Data Capture
- Flow Name: Identifies which flow failed
- Record ID: Links error to specific record for investigation
- Error Message: Captures the system fault message
- Timestamp: Auto-captured by Flow_Error_Log__c created date
✅ Centralized Error Tracking
Query all flow errors in one place:
SELECT Flow_Name__c, Record_Id__c, Error_Message__c, CreatedDate
FROM Flow_Error_Log__c
WHERE CreatedDate = TODAY
ORDER BY CreatedDate DESC
✅ Debugging Efficiency
- User reports: "Account update failed"
- Query Flow_Error_Log__c for that Account ID
- See exact error message and flow name
- Debug with full context—no need to enable debug logs first
✅ Production Monitoring
Create a dashboard showing:
- Error count by flow name
- Error trends over time
- Most common error messages
Advanced Patterns
Pattern 1: Add Alert Email
Extend Sub_LogError to send email alerts for critical errors:
<actionCalls>
<name>Send_Error_Alert</name>
<label>Send Error Alert</label>
<locationX>0</locationX>
<locationY>0</locationY>
<actionName>emailSimple</actionName>
<actionType>emailSimple</actionType>
<inputParameters>
<name>emailAddresses</name>
<value>
<stringValue>admin@company.com</stringValue>
</value>
</inputParameters>
<inputParameters>
<name>emailSubject</name>
<value>
<stringValue>Flow Error: {!varFlowName}</stringValue>
</value>
</inputParameters>
<inputParameters>
<name>emailBody</name>
<value>
<stringValue>Error occurred in flow: {!varFlowName}
Record ID: {!varRecordId}
Error Message: {!varErrorMessage}</stringValue>
</value>
</inputParameters>
</actionCalls>
Pattern 2: Integration with Platform Events
For real-time error monitoring, publish a Platform Event instead of creating a record:
<recordCreates>
<name>Publish_Error_Event</name>
<object>Flow_Error__e</object>
<inputAssignments>
<field>Flow_Name__c</field>
<value>
<elementReference>varFlowName</elementReference>
</value>
</inputAssignments>
<!-- ... other fields ... -->
</recordCreates>
Testing Your Error Logger
1. Deploy Sub_LogError
sf project deploy start --source-dir assets/subflows/ --target-org myorg
2. Create Test Flow with Intentional Error
Create a flow that attempts to update a field that doesn't exist, then check Flow_Error_Log__c.
3. Verify Error Capture
sf data query --query "SELECT Flow_Name__c, Error_Message__c FROM Flow_Error_Log__c ORDER BY CreatedDate DESC LIMIT 1" --target-org myorg
Best Practices
✅ DO:
- Use Sub_LogError in all fault paths
- Pass meaningful flow names (use naming conventions like RTF_, Auto_, etc.)
- Include record ID whenever available for context
- Review error logs regularly to identify patterns
❌ DON'T:
- Skip fault paths on DML operations
- Hardcode error messages (use $Flow.FaultMessage)
- Ignore error logs—they're your production monitoring
Related Documentation
- Subflow Library - All reusable subflows
- Orchestration Patterns - Parent-child flow architecture
- Flow Best Practices - Running mode and permissions
Questions?
For issues or questions:
- Check the troubleshooting section in README.md
- Review the skill.md for detailed workflow
- Test with the Sub_LogError template first before customizing
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Salesforce Flow Best Practices Guide
Version: 2.0.0 Last Updated: December 2025 Applies to: All flow types (Screen, Record-Triggered, Scheduled, Platform Event, Autolaunched)
This guide consolidates best practices for building maintainable, performant, and secure Salesforce Flows.
Table of Contents
Strategy & Planning
- When NOT to Use Flow ⚠️ NEW
- Pre-Development Planning ⚠️ NEW
- When to Escalate to Apex ⚠️ NEW
Flow Element Design 4. Flow Element Organization 5. Using $Record in Record-Triggered Flows 6. Querying Relationship Data 7. Query Optimization 8. Transform vs Loop Elements 9. Collection Filter Optimization
Architecture & Integration 10. When to Use Subflows 11. Custom Metadata for Business Logic ⚠️ NEW
Error Handling & Transactions 12. Three-Tier Error Handling 13. Multi-Step DML Rollback Strategy 14. Transaction Management
User Experience & Maintenance 15. Screen Flow UX Best Practices 16. Bypass Mechanism for Data Loads 17. Flow Activation Guidelines 18. Variable Naming Conventions 19. Flow & Element Descriptions ⚠️ NEW
1. When NOT to Use Flow
Before building a Flow, evaluate whether simpler declarative tools might better serve your needs. Flows add maintenance overhead and consume runtime resources—use them when their power is needed.
Prefer Declarative Configuration Over Flow
| Requirement | Better Alternative | Why |
|---|---|---|
| Same-record field calculation | Formula Field | No runtime cost, always current, no maintenance |
| Data validation with error message | Validation Rule | Built-in UI, simpler to debug, better performance |
| Parent aggregate from children | Roll-Up Summary Field | Automatic, real-time, zero maintenance |
| Field defaulting on create | Field Default Value | Native platform feature, cleaner |
| Simple required field logic | Page Layout / Field-Level Security | Declarative, no code |
| Conditional field visibility | Dynamic Forms | UI-native, better UX |
| Simple field updates on related records | Workflow Rule (if already in use) | Simpler for basic use cases |
When Flow IS the Right Choice
| Scenario | Why Flow |
|---|---|
| Complex multi-object updates | Orchestrate related changes in transaction |
| Conditional branching (3+ paths) | Decision logic beyond validation rules |
| User interaction required | Screen Flows for guided processes |
| Scheduled automation | Time-based execution |
| Platform Event handling | Real-time event processing |
| Integration callouts | HTTP callouts with error handling |
| Complex approval routing | Dynamic approval matrix |
Decision Checklist
Before creating a Flow, ask:
- Can a Formula Field calculate this value?
- Can a Validation Rule enforce this business requirement?
- Is this a simple "if changed, update field" scenario? (Consider Process Builder migration later)
- Does this require user interaction? (If no, consider automation alternatives)
- Will this run on every record save? (High-frequency = high scrutiny needed)
Rule of Thumb: If you can solve it with clicks (formula, validation, roll-up), do that first. Flows are powerful but add complexity.
<a id="2-pre-development-planning"></a>
2. Pre-Development Planning
Define business requirements and map logic before opening Flow Builder. Planning prevents rework and ensures stakeholder alignment.
Step 1: Document Requirements
Before building, answer these questions:
| Question | Purpose |
|---|---|
| What triggers this automation? | Defines Flow type (Record-Triggered, Scheduled, Screen) |
| What are ALL outcomes? | Identifies branches (happy path + edge cases) |
| Who are the affected users? | Determines User vs System Mode |
| What objects/fields are involved? | Identifies dependencies |
| Are there existing automations? | Prevents conflicts/duplicates |
Step 2: Visual Mapping
Sketch your Flow logic before building. Recommended tools:
| Tool | Cost | Best For |
|---|---|---|
| draw.io / diagrams.net | Free | Quick flowcharts, team sharing |
| Lucidchart | Paid | Professional diagrams, Salesforce shapes |
| Miro / FigJam | Freemium | Collaborative whiteboarding |
| Paper/Whiteboard | Free | Initial brainstorming |
Step 3: Identify Dependencies
| Dependency Type | Check Before Building |
|---|---|
| Custom Objects/Fields | Do they exist? Create with sf-metadata first |
| Custom Metadata Types | Bypass settings, thresholds, config values |
| Permission Sets | Required for System Mode considerations |
| External Systems | Callout endpoints, credentials |
| Other Automations | Triggers, Process Builders, other Flows on same object |
Step 4: Define Test Scenarios
Before building, list your test cases:
Test Scenarios for: Auto_Lead_Assignment
├── Happy Path: New Lead with valid data → Assigns correctly
├── Edge Case: Lead missing required field → Handles gracefully
├── Bulk Test: 200+ Leads created → No governor limits
├── Permission Test: User without edit access → Appropriate error
└── Conflict Test: Existing trigger on Lead → No infinite loop
Planning Deliverable Template
FLOW PLANNING DOCUMENT
═══════════════════════════════════════════════════
Flow Name: [Auto_Lead_Assignment]
Type: Record-Triggered (After Save)
Object: Lead
Trigger: On Create, On Update (when Status changes)
BUSINESS REQUIREMENTS:
1. Assign leads to reps based on territory
2. Send notification email to assigned rep
3. Update Lead Status to "Assigned"
ENTRY CONDITIONS:
- Status changed to 'New' OR Record is new
- NOT assigned to a rep yet
DECISION LOGIC:
- If Region = 'West' → Assign to User A
- If Region = 'East' → Assign to User B
- Else → Assign to Queue
ERROR HANDLING:
- If assignment fails → Log error, don't block save
DEPENDENCIES:
- Custom field: Region__c (exists ✓)
- Queue: Unassigned_Leads (exists ✓)
═══════════════════════════════════════════════════
3. When to Escalate to Apex
Flow is powerful, but Apex is sometimes the better tool. Know when to escalate to Invocable Apex.
Escalation Decision Matrix
| Scenario | Why Apex is Better |
|---|---|
| >5 nested decision branches | Flow becomes unreadable; Apex switch/if is cleaner |
| Complex math/string manipulation | Apex is more expressive (regex, math libraries) |
| External HTTP callouts | Better error handling, retry logic, timeout control |
| Database transactions with partial commit | Apex Savepoints for precise rollback control |
| Complex data transformations | Apex collections (Maps, Sets) are more powerful |
| Performance-critical bulk operations | Apex is faster for large datasets (10K+ records) |
| Unit testing requirements | Apex test classes provide better coverage metrics |
| Governor limit gymnastics | Apex gives finer control over limits |
Red Flags: When Flow is Fighting You
If you encounter these patterns, consider Apex:
🚩 RED FLAGS (Consider Apex Instead)
═══════════════════════════════════════════════════
❌ Building workarounds for Flow limitations
→ "I need to loop twice because Flow can't..."
❌ Flow canvas is unreadably complex
→ More than 20 elements, crossing connectors
❌ Performance issues at scale
→ Flow times out with realistic data volumes
❌ Need precise error messages
→ $Flow.FaultMessage isn't granular enough
❌ Complex JSON/XML parsing
→ Flow formulas are awkward for nested structures
❌ Multi-object transactions with partial rollback
→ Flow's all-or-nothing isn't sufficient
═══════════════════════════════════════════════════
The Hybrid Approach: Flow + Invocable Apex
Best practice: Use Flow for orchestration, Apex for complexity.
┌─────────────────────────────────────────────────────────────┐
│ HYBRID PATTERN: Flow orchestrates, Apex handles complexity │
└─────────────────────────────────────────────────────────────┘
Flow (Auto_Process_Order):
├── Start: Record-Triggered (Order)
├── Decision: Is Complex Processing Needed?
│ ├── Yes → Apex Action: ProcessComplexOrder (Invocable)
│ └── No → Simple Assignment Elements
├── Get Records: Related Line Items
├── Apex Action: CalculateTaxAndDiscount (Invocable)
└── Update Records: Order with calculated values
Benefits:
✓ Flow handles simple orchestration (readable)
✓ Apex handles complex math (maintainable)
✓ Apex is unit-testable (reliable)
✓ Admins can modify flow logic (accessible)
Invocable Apex Template
When escalating to Apex, use this pattern:
/**
* Invocable Apex for Flow: Complex Order Processing
* Called from: Auto_Process_Order Flow
*/
public class OrderProcessor {
@InvocableMethod(
label='Process Complex Order'
description='Calculates tax, discounts, and validates inventory'
category='Order Management'
)
public static List<OutputWrapper> processOrders(List<InputWrapper> inputs) {
List<OutputWrapper> results = new List<OutputWrapper>();
for (InputWrapper input : inputs) {
OutputWrapper output = new OutputWrapper();
try {
// Complex logic here
output.isSuccess = true;
output.message = 'Processed successfully';
} catch (Exception e) {
output.isSuccess = false;
output.message = e.getMessage();
}
results.add(output);
}
return results;
}
public class InputWrapper {
@InvocableVariable(required=true label='Order ID')
public Id orderId;
}
public class OutputWrapper {
@InvocableVariable(label='Success')
public Boolean isSuccess;
@InvocableVariable(label='Message')
public String message;
}
}
Rule of Thumb: If you're building workarounds for Flow limitations, use Apex. Flow should feel natural—if it doesn't, escalate.
4. Flow Element Organization
Structure your flow elements in this sequence for maintainability:
| Order | Element Type | Purpose |
|---|---|---|
| 1 | Variables & Constants | Define all data containers first |
| 2 | Start Element | Entry conditions, triggers, schedules |
| 3 | Initial Record Lookups | Retrieve needed data early |
| 4 | Formula Definitions | Define calculations before use |
| 5 | Decision Elements | Branching logic |
| 6 | Assignment Elements | Data preparation/manipulation |
| 7 | Screens (if Screen Flow) | User interaction |
| 8 | DML Operations | Create/Update/Delete records |
| 9 | Error Handling | Fault paths and rollback |
| 10 | Ending Elements | Complete flow, return outputs |
Why This Order Matters
- Readability: Reviewers can follow the logical flow
- Maintainability: Easy to locate elements by function
- Debugging: Errors trace back to predictable locations
<a id="5-using-record-in-record-triggered-flows"></a>
5. Using $Record in Record-Triggered Flows
When your flow is triggered by a record change, use $Record to access field values instead of querying the same object again.
⚠️ CRITICAL: $Record vs $Record__c
Do NOT confuse Flow's $Record with Process Builder's $Record__c.
| Variable | Platform | Meaning |
|---|---|---|
$Record |
Flow | Single record that triggered the flow |
$Record__c |
Process Builder (legacy) | Collection of records in trigger batch |
Common Mistake: Developers migrating from Process Builder try to loop over $Record__c in Flows. This doesn't work because:
$Record__cdoes not exist in Flows$Recordin Flows is a single record, not a collection- The platform handles bulk batching automatically - you don't need to loop
Correct Approach: Use $Record directly without loops:
Decision: {!$Record.StageName} equals "Closed Won"
Assignment: Set rec_Task.WhatId = {!$Record.Id}
Create Records: rec_Task
Anti-Pattern (Avoid)
Trigger: Account record updated
Step 1: Get Records → Query Account where Id = {!$Record.Id}
Step 2: Use queried Account fields
Problems:
- Wastes a SOQL query (you already have the record!)
- Adds unnecessary complexity
- Can cause timing issues with stale data
Best Practice
Trigger: Account record updated
Step 1: Use {!$Record.Name}, {!$Record.Industry} directly
Benefits:
- Zero additional SOQL queries
- Always has current field values
- Simpler, more readable flow
When You DO Need to Query
Query the trigger object only when you need:
- Related records (e.g., Account's Contacts)
- Fields not included in the trigger context
- Historical comparison (
$Record__Prior)
6. Querying Relationship Data
⚠️ Get Records Does NOT Support Parent Traversal
Critical Limitation: You CANNOT query parent relationship fields in Flow's Get Records.
What Doesn't Work
Get Records: User
Fields: Id, Name, Manager.Name ← FAILS!
Error: "The field 'Manager.Name' for the object 'User' doesn't exist."
The Solution: Two-Step Pattern
Query the child object first, then query the parent using the lookup ID:
Step 1: Get Records → User
Fields: Id, Name, ManagerId
Store in: rec_User
Step 2: Get Records → User
Filter: Id equals {!rec_User.ManagerId}
Fields: Id, Name
Store in: rec_Manager
Step 3: Use {!rec_Manager.Name} in your flow
Common Relationship Queries That Need This Pattern
| Child Object | Parent Field | Two-Step Approach |
|---|---|---|
| Contact | Account.Name | Get Contact → Get Account by AccountId |
| Case | Account.Owner.Email | Get Case → Get Account → Get User |
| Opportunity | Account.Industry | Get Opportunity → Get Account by AccountId |
| User | Manager.Name | Get User → Get User by ManagerId |
Why This Matters
- Flow's Get Records uses simple field retrieval, not SOQL relationship queries
- This is different from Apex where you can write
SELECT Account.Name FROM Contact - Always check for null on the parent record before using its fields
7. Query Optimization
Use 'In' and 'Not In' Operators
When filtering against a collection of values, use In or Not In operators instead of multiple OR conditions.
Best Practice:
Get Records where Status IN {!col_StatusValues}
Avoid:
Get Records where Status = 'Open' OR Status = 'Pending' OR Status = 'Review'
Always Add Filter Conditions
Every Get Records element should have filter conditions to:
- Limit the result set
- Improve query performance
- Avoid hitting governor limits
Use Indexed Fields for Large Data Volumes
For orgs with 100K+ records on an object, filter on indexed fields to ensure fast query performance.
Always Indexed Fields
| Field Type | Examples | Notes |
|---|---|---|
| Id | Record ID | Primary key, fastest |
| Name | Account Name, Contact Name | Standard name field |
| CreatedDate | - | Useful for recent records |
| SystemModstamp | - | Last modified timestamp |
| RecordTypeId | - | If using Record Types |
| OwnerId | - | User lookup |
Custom Indexed Fields
| Field Type | Notes |
|---|---|
| External ID fields | Automatically indexed |
| Lookup/Master-Detail fields | Relationship fields are indexed |
| Custom fields with indexing | Request via Salesforce Support |
| Unique fields | Automatically indexed |
Performance Impact
┌─────────────────────────────────────────────────────────────────┐
│ QUERY PERFORMANCE: Indexed vs Non-Indexed │
└─────────────────────────────────────────────────────────────────┘
❌ NON-INDEXED FILTER (Slow on large objects):
Get Records: Account
Filter: Custom_Text__c = "ValueABC"
→ Full table scan = slow + timeout risk
✅ INDEXED FILTER (Fast at any scale):
Get Records: Account
Filter: External_Id__c = "ValueABC"
→ Index lookup = milliseconds
When to Request Custom Indexing
Contact Salesforce Support to request indexing when:
- Object has 100K+ records
- Query frequently filters on a specific field
- Flow timeouts occur with non-indexed filters
Tip: Use
SELECT Id FROM Object WHERE Field = 'value'in Developer Console to test query performance before building the Flow.
Use getFirstRecordOnly
When you expect a single record (e.g., looking up by unique ID), enable getFirstRecordOnly:
- Improves performance
- Clearer intent
- Simpler variable handling
Avoid storeOutputAutomatically
When storeOutputAutomatically="true", ALL fields are retrieved and stored:
Risks:
- Exposes sensitive data unintentionally
- Impacts performance with large objects
- Security issue in screen flows (external users see all data)
Fix: Explicitly specify only the fields you need in the Get Records element.
8. Transform vs Loop Elements
When processing collections, choosing between Transform and Loop elements significantly impacts performance and maintainability.
Quick Decision Rule
Shaping data → Use Transform (30-50% faster) Making decisions per record → Use Loop
When to Use Transform
Transform is the right choice for:
| Use Case | Example |
|---|---|
| Mapping collections | Contact[] → OpportunityContactRole[] |
| Bulk field assignments | Set Status = "Processed" for all records |
| Simple formulas | Calculate FullName from FirstName + LastName |
| Preparing records for DML | Build collection for Create Records |
When to Use Loop
Loop is required when:
| Use Case | Example |
|---|---|
| Per-record IF/ELSE | Different processing based on Amount threshold |
| Counters/flags | Count records meeting criteria |
| State tracking | Running totals, comma-separated lists |
| Varying business rules | Different logic paths per record type |
Visual Comparison
❌ ANTI-PATTERN: Loop for simple field mapping
Get Records → Loop → Assignment → Add to Collection → Create Records
(5 elements, client-side iteration)
✅ BEST PRACTICE: Transform for field mapping
Get Records → Transform → Create Records
(3 elements, server-side bulk operation, 30-50% faster)
Performance Impact
Transform processes the entire collection server-side as a single bulk operation, while Loop iterates client-side. For collections of 100+ records, Transform can be 30-50% faster.
XML Recommendation
⚠️ Create Transform elements in Flow Builder UI, then deploy. Transform XML is complex with strict ordering—do not hand-write.
See Transform vs Loop Guide for detailed decision criteria, examples, and testing strategies.
9. Collection Filter Optimization
Collection Filter is a powerful tool for reducing governor limit usage by filtering in memory instead of making additional SOQL queries.
The Pattern
Instead of multiple Get Records calls, query once and filter in memory:
┌─────────────────────────────────────────────────────────────────────────┐
│ ❌ ANTI-PATTERN: Multiple Get Records calls │
└─────────────────────────────────────────────────────────────────────────┘
For each Account in loop:
→ Get Records: Contacts WHERE AccountId = {!current_Account.Id}
→ Process contacts...
Problem: N SOQL queries (one per Account) = Governor limit risk!
┌─────────────────────────────────────────────────────────────────────────┐
│ ✅ BEST PRACTICE: Query once + Collection Filter │
└─────────────────────────────────────────────────────────────────────────┘
1. Get Records: ALL Contacts WHERE AccountId IN {!col_AccountIds}
→ 1 SOQL query total
2. Loop through Accounts:
→ Collection Filter: Contacts WHERE AccountId = {!current_Account.Id}
→ Process filtered contacts (in-memory, no SOQL!)
Benefits
| Metric | Multiple Queries | Query Once + Filter |
|---|---|---|
| SOQL Queries | N (one per parent) | 1 |
| Performance | Slow | Fast |
| Governor Risk | High | Low |
| Scalability | Poor | Excellent |
Implementation Steps
- Collect parent IDs into a collection variable
- Single Get Records using
INoperator with ID collection - Loop through parents, using Collection Filter to get related records
- Process filtered subset in each iteration
When to Use
- Parent-child processing (Account → Contacts, Opportunity → Line Items)
- Batch operations where you need related records
- Any scenario requiring records from the same object for multiple parents
Governor Limit Savings
With Collection Filter, you can process thousands of related records with a single SOQL query instead of hitting the 100-query limit.
10. When to Use Subflows
Use subflows for:
1. Reusability
Same logic needed in multiple flows? Extract it to a subflow.
- Error logging
- Email notifications
- Common validations
2. Complex Orchestration
Break large flows into manageable pieces:
- Main flow orchestrates
- Subflows handle specific responsibilities
- Easier to test individually
3. Permission Elevation
When a flow running in user context needs elevated permissions:
- Main flow runs in user context
- Subflow runs in system context for specific operations
- Maintains security while enabling functionality
4. Organizational Clarity
If your flow diagram is unwieldy:
- Extract logical sections into subflows
- Name subflows descriptively
- Document the orchestration pattern
Subflow Naming Convention
Use the Sub_ prefix:
Sub_LogErrorSub_SendEmailAlertSub_ValidateRecordSub_BulkUpdater
11. Custom Metadata for Business Logic
Store frequently changing business logic values in Custom Metadata Types (CMDT) rather than hard-coding them in Flow. This enables admins to change thresholds, settings, and routing logic without modifying the Flow.
Why Use CMDT for Business Logic
| Benefit | Description |
|---|---|
| No deployment needed | Change values in Setup, no Flow modification |
| Environment-specific | Different values per sandbox/production |
| Audit trail | Changes tracked in Setup Audit Trail |
| Admin-friendly | Non-developers can update business rules |
| Testable | CMDT records are accessible in test context |
Two Access Patterns
| Pattern | Syntax | SOQL Count | Use When |
|---|---|---|---|
| Formula Reference | $CustomMetadata.Type__mdt.Record.Field__c |
0 | Single known record, simple value |
| Get Records Query | Get Records → CMDT object | 1 | Multiple records, dynamic filtering |
Formula Pattern (Preferred for Single Values)
- No SOQL consumed - platform resolves at runtime
- Direct reference in conditions/assignments
- Syntax:
{!$CustomMetadata.Flow_Settings__mdt.Discount_Threshold.Numeric_Value__c}
Decision: Check_Threshold
├── Condition: {!$Record.Amount} >= {!$CustomMetadata.Flow_Settings__mdt.Discount_Threshold.Numeric_Value__c}
└── Outcome: Apply_Discount
Get Records Pattern (For Dynamic Queries)
- Consumes 1 SOQL per query
- Enables filtering, multiple record retrieval
- Visible in Flow debug logs for troubleshooting
- Useful when CMDT record name is dynamic or you need to iterate
Get Records: Flow_Settings__mdt
├── Filter: Category__c = "Discount"
├── Store All Records: col_DiscountSettings
└── Use in Loop or Transform
Rule of Thumb: Use Formula Reference when you know the exact CMDT record at design time. Use Get Records when the record selection is dynamic or you need multiple records.
What to Store in CMDT
| Value Type | Example CMDT Field | ⚠️ Key Guidance |
|---|---|---|
| Business Thresholds | Discount_Threshold__c, Max_Approval_Amount__c |
Ideal for values that change quarterly or less |
| Feature Toggles | Enable_Auto_Assignment__c |
Boolean flags for gradual rollouts |
| Record Type Names | RecordType_DeveloperName__c |
Store DeveloperName, NOT 15/18-char IDs |
| Queue/User Names | Assignment_Queue_Name__c |
Store DeveloperName, resolve ID at runtime |
| Email Recipients | Notification_Email__c, Template_Name__c |
Store template API names, not IDs |
| URLs/Endpoints | External_API_Endpoint__c |
Enables sandbox vs production differences |
| Picklist Mappings | Source_Value__c → Target_Value__c |
Great for value translations |
⚠️ CRITICAL: Never Store Salesforce IDs in CMDT
Salesforce 15/18-character IDs (RecordTypeId, QueueId, UserId, ProfileId) are org-specific. The same Queue has different IDs in sandbox vs production. Storing IDs in CMDT causes deployment failures.
❌ Wrong:
Queue_Id__c = '00G5f000004XXXX'✅ Right:Queue_Name__c = 'Support_Queue'→ Resolve ID at runtime with Get Records
Runtime ID Resolution Pattern
When you need to route to a Queue, User, or RecordType stored in CMDT:
1. Get CMDT Value:
Formula: {!$CustomMetadata.Flow_Settings__mdt.Support_Queue.Queue_Name__c}
→ Returns: "Support_Queue" (DeveloperName)
2. Get Records: Group (Queue)
Filter: DeveloperName = {!var_QueueName} AND Type = 'Queue'
Store: rec_Queue
3. Assignment:
Set {!$Record.OwnerId} = {!rec_Queue.Id}
Common Use Cases
| Use Case | CMDT Field Example | Flow Usage |
|---|---|---|
| Discount thresholds | Discount_Threshold__c = 10000 |
Decision: Amount > {!$CustomMetadata...} |
| Feature toggles | Enable_Auto_Assignment__c = true |
Decision: Feature enabled? |
| Approval limits | Max_Approval_Amount__c = 50000 |
Route based on amount threshold |
| Email recipients | Notification_Email__c |
Send email to CMDT value |
| SLA thresholds | SLA_Warning_Hours__c = 24 |
Decision: Hours > threshold |
| API endpoints | External_API_Endpoint__c |
HTTP Callout URL |
Implementation Pattern
Step 1: Create Custom Metadata Type
Object: Flow_Settings__mdt
Fields:
├── Setting_Name__c (Text, Unique)
├── Numeric_Value__c (Number)
├── Text_Value__c (Text)
├── Boolean_Value__c (Checkbox)
└── Description__c (Text Area)
Step 2: Create Records
Record: Discount_Threshold
├── Setting_Name__c = "Discount_Threshold"
├── Numeric_Value__c = 10000
├── Text_Value__c = null
├── Boolean_Value__c = false
└── Description__c = "Minimum order amount for automatic discount"
Step 3: Reference in Flow
Decision Element: Check_Discount_Eligibility
├── Condition: {!$Record.Amount} >= {!$CustomMetadata.Flow_Settings__mdt.Discount_Threshold.Numeric_Value__c}
│ └── Outcome: Apply_Discount
└── Default: No_Discount
Best Practices
| Practice | Reason |
|---|---|
| Use descriptive DeveloperNames | Discount_Threshold not Setting_1 |
| Document in Description field | Future maintainers understand purpose |
| Group related settings | One CMDT type per domain (Sales, Service, etc.) |
| Include in deployment packages | CMDT records are metadata, deploy with code |
| Test with realistic values | Verify Flow behavior with production thresholds |
Identifying Hard-Coded Candidates (Migration Checklist)
Review existing flows for these hard-coded patterns that should migrate to CMDT:
HARD-CODED PATTERN AUDIT
═══════════════════════════════════════════════════════════
📋 CHECK YOUR FLOWS FOR:
□ 15/18-character Salesforce IDs
└─ RecordTypeIds, QueueIds, UserIds, ProfileIds
└─ Example: OwnerId = '005...' → Store Queue DeveloperName
□ Hardcoded URLs or endpoints
└─ HTTP callout URLs, redirect paths
└─ Example: endpoint = 'https://api.prod...' → Store in CMDT
□ Magic numbers (thresholds, limits, percentages)
└─ Discount rates, approval limits, SLA hours
└─ Example: Amount > 10000 → Use CMDT threshold
□ Email addresses in Send Email actions
└─ Notification recipients, CC lists
└─ Example: To = 'admin@company.com' → Store in CMDT
□ Profile/Permission Set names
└─ Used in Decision conditions
└─ Store as text, query Profile/PermissionSet at runtime
□ Object API names used in dynamic references
└─ Hard-coded object strings for generic patterns
□ Picklist values used in conditions
└─ Values that might change across regions/deployments
═══════════════════════════════════════════════════════════
Validator Note: The sf-flow validator automatically flags
HardcodedIdandHardcodedUrlpatterns during analysis.
When NOT to Use CMDT
| Scenario | Better Alternative |
|---|---|
| User-specific preferences | Custom Settings (Hierarchy) |
| Frequently changing data | Custom Object with query |
| Large datasets (1000+ records) | Custom Object |
| Binary file storage | Static Resource or Files |
Tip: CMDT is ideal for business rules that change quarterly or less. For daily-changing values, use Custom Objects or Custom Settings.
Deployment vs Data Load Distinction
CMDT records are metadata, not data. This has important implications:
| Aspect | Custom Metadata Type | Custom Object / Custom Setting |
|---|---|---|
| Move between orgs | Change Sets, Metadata API, sf deploy | Data Loader, sf data import |
| Update in production | Setup → Custom Metadata Types | Data operations (update records) |
| Included in packages | ✅ Yes (managed/unmanaged) | ❌ No (data must be seeded separately) |
| Test context access | ✅ Accessible without @TestSetup |
Requires test data creation |
Common Mistake: Trying to use Data Loader to update CMDT values. CMDT records are deployed as metadata—use Change Sets, Metadata API (
sf project deploy), or Setup UI to modify values between environments.
<a id="12-three-tier-error-handling"></a>
12. Three-Tier Error Handling
Implement comprehensive error handling at three levels:
Tier 1: Input Validation (Pre-Execution)
When: Before any DML operations What to Check:
- Null/empty required values
- Business rule prerequisites
- Data format validation
Action: Show validation error screen or set error output variable
Tier 2: DML Error Handling (During Execution)
When: On every DML element (Create, Update, Delete) What to Do:
- Add fault paths to ALL DML elements
- Capture
{!$Flow.FaultMessage}for context - Include record IDs and operation type in error messages
Action: Route to error handler, prepare for rollback
Tier 3: Rollback Handling (Post-Failure)
When: After a DML failure when prior operations succeeded What to Do:
- Delete records created earlier in the transaction
- Restore original values if updates failed
- Log the failure for debugging
Action: Execute rollback, notify user/admin
Error Message Best Practice
Include context in every error message:
"Failed to create Contact for Account {!rec_Account.Id}: {!$Flow.FaultMessage}"
"Update failed on Opportunity {!rec_Opportunity.Id} during {!var_CurrentOperation}"
<a id="13-multi-step-dml-rollback-strategy"></a>
13. Multi-Step DML Rollback Strategy
When a flow performs multiple DML operations, implement rollback paths.
Pattern: Primary → Dependent → Rollback Chain
Step 1: Create Primary Record (e.g., Account)
- On success → Continue to step 2
- On failure → Show error, stop flow
Step 2: Create Dependent Records (e.g., Contacts, Opportunities)
- On success → Continue to step 3
- On failure → DELETE primary record, show error
Step 3: Update Related Records
- On success → Complete flow
- On failure → DELETE dependents, DELETE primary, show error
Implementation Pattern
1. Create Account → Store ID in var_AccountId
2. Create Contacts → On fault: Delete Account using var_AccountId
3. Create Opportunities → On fault: Delete Contacts, Delete Account
4. Success → Return output variables
Error Message Pattern
Use errorMessage output variable to surface failures:
"Failed to create Account: {!$Flow.FaultMessage}"
"Failed to create Contact: {!$Flow.FaultMessage}. Account rolled back."
14. Transaction Management
Understanding Flow Transactions
- All DML in a flow runs in a single transaction (unless using async)
- If any DML fails, all changes roll back automatically
- Use this to your advantage for data integrity
Save Point Pattern
For complex multi-step flows where you need manual rollback control:
- Create primary records
- Store IDs of created records in a collection
- Create dependent records
- On failure → Use stored IDs for manual rollback
Transaction Limits to Consider
| Limit | Value |
|---|---|
| DML statements per transaction | 150 |
| SOQL queries per transaction | 100 |
| Records retrieved by SOQL | 50,000 |
| DML rows per transaction | 10,000 |
Screen Flow Transaction Boundaries
In Screen Flows, each screen element breaks the transaction boundary. DML committed before a screen element cannot be rolled back after the screen. This is a critical difference from Record-Triggered Flows (which run in a single transaction).
Impact: If a Screen Flow creates an Account on Screen 1, then the user encounters an error on Screen 2, the Account is already committed and cannot be automatically rolled back.
Mitigation:
- Collect ALL input across screens first (store in Flow variables)
- Perform ALL DML after the final screen
- Use the Roll Back Records element for multi-step forms that need atomicity
- For complex forms, consider a single-screen design with reactive components
Document Transaction Boundaries
Add comments in flow description:
TRANSACTION: Creates Account → Creates Contact → Updates related Opportunities
15. Screen Flow UX Best Practices
Progress Indicators
For multi-step flows (3+ screens):
- Use Screen component headers to show "Step X of Y"
- Consider visual progress bars for long wizards
- Update progress on each screen transition
Stage Resource for Multi-Screen Flows
The Stage resource provides visual progress tracking across multiple screens, showing users where they are in a multi-step process.
When to Use Stage
- Flows with 3+ screens that represent distinct phases
- Onboarding wizards (Identity → Configuration → Confirmation)
- Order processes (Cart → Shipping → Payment → Review)
- Application workflows with logical sections
How Stages Work
- Define stages in your flow resources (Stage elements)
- Assign current stage using Assignment element at each phase transition
- Display progress using the Stage component in screens
Stage Example
Flow: New Customer Onboarding
Stages:
1. Identity (collect customer info)
2. Configuration (set preferences)
3. Payment (billing details)
4. Confirmation (review and submit)
Each screen shows visual indicator: ● ○ ○ ○ → ● ● ○ ○ → ● ● ● ○ → ● ● ● ●
Benefits
| Feature | Benefit |
|---|---|
| Visual progress | Users know how far along they are |
| Reduced abandonment | Clear expectation of remaining steps |
| Better UX | Professional wizard-like experience |
| Navigation context | Users understand their position |
Implementation Tips
- Keep stage names short (1-3 words)
- Use consistent naming pattern (nouns: "Identity", "Payment" vs verbs: "Collect Info", "Enter Payment")
- Consider allowing users to click back to previous stages (if safe)
Button Design
Naming Pattern
Use: Action_[Verb]_[Object]
Action_Save_ContactAction_Submit_ApplicationAction_Cancel_Request
Button Ordering
- Primary action first (Submit, Save, Confirm)
- Secondary actions next (Save Draft, Back)
- Tertiary/Cancel last (Cancel, Exit)
Navigation Controls
Standard Navigation Pattern
| Button | Position | When to Show |
|---|---|---|
| Previous | Left | After first screen (if safe) |
| Cancel | Left | Always |
| Next | Right | Before final screen |
| Finish/Submit | Right | Final screen only |
When to Disable Back Button
Disable "Previous" when returning would:
- Cause duplicate record creation
- Lose unsaved complex data
- Break transaction integrity
- Confuse business process state
Screen Instructions
For complex screens, add instruction text at the top:
- Use Display Text component
- Keep instructions concise (1-2 sentences)
- Highlight required fields or important notes
Example: "Complete all required fields (*) before proceeding."
Performance Tips
- Lazy Loading: Don't load all data upfront; query as needed per screen
- Minimize Screens: Each screen = user wait time; combine where logical
- Avoid Complex Formulas: In screen components (impacts render time)
- LWC for Complex UI: Consider Lightning Web Components for rich interactions
16. Bypass Mechanism for Data Loads
When loading large amounts of data, flows can cause performance issues. Implement a bypass mechanism.
Option A: Custom Permissions (Recommended)
Custom Permissions provide the most scalable bypass mechanism. They can be assigned via Permission Sets and checked in Flow entry conditions.
Setup
- Create Custom Permission:
Bypass_Flow__c(Setup → Custom Permissions) - Assign to a Permission Set (e.g., "Data Load Bypass")
- Use in Flow entry conditions (not Decision elements):
Entry Condition Formula: NOT({!$Permission.Bypass_Flow__c})
This prevents the flow from executing at all for users with the bypass permission — more efficient than a Decision element inside the flow.
For Decision Elements (Alternative)
If you need conditional bypass within the flow (not at entry):
Condition: {!$Permission.Bypass_Flow__c} = true
- If true → End flow early
- If false → Continue normal processing
Why Custom Permissions > Custom Metadata bypass: Custom Permissions are user-assignable via Permission Sets, don't require metadata deployment to toggle, and work consistently across Apex, Flow, and Validation Rules.
Option B: Custom Metadata (Legacy)
Create Flow_Bypass_Settings__mdt with fields:
Bypass_Flows__c(Checkbox)Flow_API_Name__c(Text) - optional, for granular control
Condition: {!$CustomMetadata.Flow_Bypass_Settings__mdt.Default.Bypass_Flows__c} = true
Use Cases
- Data migrations
- Bulk data loads via Data Loader
- Integration batch processing
- Initial org setup/seeding
Best Practice
- Document which flows support bypass
- Ensure bypass is disabled after data load completes
- Consider logging when bypass is active
17. Flow Activation Guidelines
When to Keep Flows in Draft
- During development and testing
- Before user acceptance testing (UAT) is complete
- When dependent configurations aren't deployed yet
Deployment Recommendation
- Deploy flows as Draft initially
- Validate in target environment
- Test with representative data
- Activate only after verification
- Keep previous version as backup before activating new version
Scheduled Flow Considerations
Scheduled flows run automatically without user interaction:
- Test thoroughly before activation
- Verify schedule frequency is correct
- Ensure error notifications are configured
- Monitor first few executions
18. Variable Naming Conventions
Use consistent prefixes for all variables:
| Prefix | Purpose | Example |
|---|---|---|
var_ |
Regular variables | var_AccountName |
col_ |
Collections | col_ContactIds |
rec_ |
Record variables | rec_Account |
inp_ |
Input variables | inp_RecordId |
out_ |
Output variables | out_IsSuccess |
Why Prefixes Matter
- Clarity: Immediately understand variable type
- Debugging: Easier to trace values in debug logs
- Maintenance: New developers understand intent quickly
- Consistency: Team-wide standards reduce confusion
Element Naming
For flow elements (decisions, assignments, etc.):
- Use
PascalCase_With_Underscores - Be descriptive:
Check_Account_TypenotDecision_1 - Include context:
Get_Related_ContactsnotGet_Records
19. Flow & Element Descriptions
Clear descriptions are essential for maintenance, collaboration, and Agentforce integration. AI agents use Flow descriptions to understand and select appropriate automations.
Flow Description (Critical for Agentforce)
Why This Matters
| Consumer | How They Use Descriptions |
|---|---|
| Agentforce Agents | AI uses descriptions to understand what automation does and when to invoke it |
| Future Developers | Quick understanding without reading the entire flow |
| Flow Orchestrator | Discovery of available subflows |
| Governance Tools | Auditing and documentation generation |
| Setup Search | Finding flows by purpose |
What to Include in Flow Description
Every Flow description should contain:
- Purpose: One sentence explaining what the flow does
- Trigger: When/how the flow is invoked
- Objects: Which objects are read/written
- Outcome: What changes when the flow completes
- Dependencies: Any required configurations or prerequisites
Examples
✅ GOOD DESCRIPTION:
───────────────────────────────────────────────────────────────
"Automatically assigns new Leads to the appropriate sales rep
based on territory and product interest. Updates Lead Owner,
sets Assignment_Date__c, and sends notification email to the
assigned rep. Triggered on Lead creation when Status = 'New'.
Requires Territory__c field and Lead_Assignment_Queue__c queue."
───────────────────────────────────────────────────────────────
❌ BAD DESCRIPTION:
"Lead flow"
"Auto assignment"
"Created by Admin"
Description Template
[ACTION] [OBJECT(S)] [CONDITION].
[WHAT CHANGES]. [TRIGGER/SCHEDULE].
[DEPENDENCIES if any].
Examples using template:
- "Creates Task and sends email when Opportunity Stage changes to Closed Won. Updates Account Last_Deal_Date__c. Runs after Opportunity update."
- "Validates Contact email format and enriches with external data. Blocks save if validation fails. Runs before Contact insert/update."
Element Descriptions
Add descriptions to complex elements (Decisions, Assignments, Get Records, Loops) to explain why the element exists, not just what it does.
When to Add Element Descriptions
| Element Type | Add Description When... |
|---|---|
| Decision | Logic has business meaning beyond obvious field comparison |
| Get Records | Query has specific filter reasoning |
| Assignment | Calculation or transformation isn't self-evident |
| Loop | Processing order or exit conditions matter |
| Subflow | Purpose of delegation isn't obvious |
Element Description Format
WHY: [Business reason this element exists]
WHAT: [Technical summary if complex]
EDGE CASE: [Special handling if applicable]
Examples
Decision: Check_Discount_Eligibility
Description: "Customers with >$100K annual revenue OR
Premium tier get automatic 15% discount. Edge case:
New customers without revenue history default to no discount."
Get Records: Get_Active_Contracts
Description: "Retrieves only contracts expiring in next 90 days
to avoid processing historical data. Filtered by Status=Active
to reduce collection size for bulk safety."
Assignment: Calculate_Renewal_Date
Description: "Adds 365 days to current contract end date.
Uses formula to handle leap years. Returns null if
original end date is null (new contracts)."
Benefits of Good Descriptions
| Benefit | Impact |
|---|---|
| 6-month test | Can you understand the flow in 6 months? |
| Handoff ready | New team member can maintain without meetings |
| Agentforce-ready | AI can discover and use your flows correctly |
| Audit-friendly | Compliance reviews understand business logic |
| Debug faster | Element descriptions explain expected behavior |
Rule of Thumb: If you had to explain this Flow or element to a colleague, put that explanation in the description.
Quick Reference Checklist
Record-Triggered Flow Essentials
- Use
$Recorddirectly - do NOT create loops over triggered records - Never use
$Record__c(Process Builder pattern, doesn't exist in Flows) - Platform handles bulk batching - you don't need manual loops
Get Records Best Practices
- Use
$Recordinstead of querying trigger object - Add filters to all Get Records elements
- Enable
getFirstRecordOnlywhen expecting single record - Disable
storeOutputAutomatically(specify fields explicitly) - For relationship data: Use two-step query pattern (child → parent by ID)
- Never query
Parent.Fieldin queriedFields (not supported)
Error Handling & DML
- Add fault paths to all DML operations
- Implement rollback for multi-step DML
- Capture
$Flow.FaultMessagein error handlers
Naming & Organization
- Use variable naming prefixes (
var_,col_,rec_, etc.) - Add progress indicators to multi-screen flows
Testing & Deployment
- Test with bulk data (200+ records)
- Keep flows in Draft until fully tested
- Always use sf-deploy skill - never direct CLI commands
Related Documentation
- Transform vs Loop Guide - When to use each element
- Flow Quick Reference - Comprehensive cheat sheet
- Orchestration Guide - Parent-child and sequential patterns
- Subflow Library - Reusable subflow templates
- Testing Guide - Comprehensive testing strategies
- Governance Checklist - Security and compliance
- XML Gotchas - Common XML pitfalls
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flow Quick Reference
A comprehensive cheat sheet for Salesforce Flow development. Use this guide for quick decisions on flow types, elements, and variables.
Flow Type Selection Decision Tree
┌─────────────────────────────────────────────────────────────────────────┐
│ WHICH FLOW TYPE SHOULD I USE? │
└─────────────────────────────────────────────────────────────────────────┘
Need to gather user input?
├─ YES ──────────────────────────────────────────► SCREEN FLOW
│ └─ Foreground execution
│ └─ Users see and interact
│
└─ NO ─► Need multi-step, multi-user workflow?
├─ YES ─────────────────────────────────► FLOW ORCHESTRATION
│ └─ Multi-stage approvals
│ └─ Sequential user tasks
│
└─ NO ─► Record created, updated, or deleted?
├─ YES ────────────────────────► RECORD-TRIGGERED FLOW
│ │
│ ├─ Modify same record? ──► Before-Save Trigger
│ │ └─ No DML required
│ │ └─ Field updates, validation
│ │
│ └─ Modify related records? ► After-Save Trigger
│ └─ DML on other objects
│ └─ Callouts, emails
│
└─ NO ─► Run on a schedule?
├─ YES ──────────────► SCHEDULE-TRIGGERED FLOW
│ └─ Runs once/daily/weekly
│ └─ Batch processing
│
└─ NO ─► Platform Event received?
├─ YES ─────► PLATFORM EVENT-TRIGGERED
│ └─ Event-driven automation
│ └─ Async processing
│
└─ NO ──────► AUTOLAUNCHED FLOW
└─ Called from Apex/REST
└─ Called from other flows
└─ Agent actions
Flow Type Quick Reference
| Flow Type | Trigger | Use Case | Execution |
|---|---|---|---|
| Screen Flow | User clicks button/link | Forms, wizards, guided processes | Foreground |
| Record-Triggered (Before) | Record DML (before commit) | Same-record validation, field defaults | Background |
| Record-Triggered (After) | Record DML (after commit) | Related records, callouts, emails | Background |
| Schedule-Triggered | Time-based (cron) | Batch updates, cleanup, notifications | Background |
| Platform Event-Triggered | Platform Event published | Event-driven processing, async work | Background |
| Autolaunched | Code/Flow invocation | Subflows, Apex-called, REST API | Background |
| Flow Orchestration | Multi-step workflow | Approvals, multi-user processes | Background |
Flow Elements Reference
Logic Elements (Flow Control)
┌─────────────────────────────────────────────────────────────────────────┐
│ LOGIC ELEMENTS │
├──────────────────┬──────────────────────────────────────────────────────┤
│ Assignment │ Set variable values; update data as flow progresses │
│ │ Example: var_Total = var_Subtotal * 1.08 │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Decision │ IF/THEN/ELSE routing; branch flow paths │
│ │ Example: If Amount > 10000 → High Priority path │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Loop │ Iterate through collections; per-record processing │
│ │ Example: For each Contact in collection... │
│ │ USE WHEN: Per-record decisions, counters, flags │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Collection Sort │ Organize collection by specified field │
│ │ Example: Sort Accounts by AnnualRevenue DESC │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Collection Filter│ Create filtered subset without new SOQL query │
│ │ Example: Filter Opps where Amount > 5000 │
│ │ TIP: Use after Get Records to reduce governor use │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Transform │ Map fields and transform collections (bulk) │
│ │ Example: Map Contact fields → Lead fields │
│ │ USE WHEN: Data mapping, bulk assignments │
│ │ 30-50% faster than Loop for field mapping │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Custom Error │ Display error message and stop flow execution │
│ │ Example: "Amount must be greater than zero" │
└──────────────────┴──────────────────────────────────────────────────────┘
Data Elements (CRUD Operations)
┌─────────────────────────────────────────────────────────────────────────┐
│ DATA ELEMENTS │
├──────────────────┬──────────────────────────────────────────────────────┤
│ Get Records │ Query database (SOQL equivalent) │
│ │ TIP: Use filters! Unfiltered = governor limit risk │
│ │ TIP: Can't traverse parent fields (use 2-step) │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Create Records │ Insert new records; supports collections │
│ │ Example: Create Case from Opportunity data │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Update Records │ Modify existing records │
│ │ In Before-Save: No DML needed for trigger record │
│ │ In After-Save: Use for related records │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Delete Records │ Remove records from database │
│ │ Example: Delete old cases older than 2 years │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Roll Back Records│ Undo pending changes in current transaction │
│ │ Use in fault paths for multi-step DML rollback │
└──────────────────┴──────────────────────────────────────────────────────┘
Interaction Elements (UI & External)
┌─────────────────────────────────────────────────────────────────────────┐
│ INTERACTION ELEMENTS │
├──────────────────┬──────────────────────────────────────────────────────┤
│ Screen │ UI canvas with standard/custom components │
│ │ Supports: Text, Input, Picklist, Checkbox, LWC │
│ │ TIP: Use Stage resource for multi-screen progress │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Action │ Call external processes │
│ │ Built-in: Send Email, Submit for Approval │
│ │ Custom: Apex @InvocableMethod │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Subflow │ Call another flow with input/output variables │
│ │ Use for: Reusable logic, modular architecture │
│ │ See: references/subflow-library.md for pre-built subflows │
├──────────────────┼──────────────────────────────────────────────────────┤
│ Wait │ Pause flow execution until condition met │
│ │ Types: Duration, Date, Platform Event │
│ │ See: references/wait-patterns.md for XML patterns │
└──────────────────┴──────────────────────────────────────────────────────┘
Variable Types Reference
┌─────────────────────────────────────────────────────────────────────────┐
│ FLOW RESOURCE TYPES │
├────────────────────┬────────────────────────────────────────────────────┤
│ Type │ Description & Use Case │
├────────────────────┼────────────────────────────────────────────────────┤
│ Variable │ Mutable container for data that changes │
│ │ Types: Text, Number, Date, DateTime, Boolean, │
│ │ Currency, Record, Collection │
│ │ Naming: var_AccountName, col_Contacts, rec_Lead │
├────────────────────┼────────────────────────────────────────────────────┤
│ Constant │ Immutable value (set once, never changes) │
│ │ Use: Fixed rates, status codes, thresholds │
│ │ Example: con_TaxRate = 0.08 │
├────────────────────┼────────────────────────────────────────────────────┤
│ Formula │ Calculated result from variables/constants │
│ │ Example: frm_Total = var_Subtotal * (1 + con_Tax) │
├────────────────────┼────────────────────────────────────────────────────┤
│ Text Template │ Dynamic text with variable interpolation │
│ │ Use: Email bodies, notifications, messages │
│ │ Example: "Hello {!var_FirstName}, order ready" │
├────────────────────┼────────────────────────────────────────────────────┤
│ Choice │ Single picklist/radio option (label + value) │
│ │ Use: Screen flow input controls │
│ │ Example: { Label: "High", Value: "1" } │
├────────────────────┼────────────────────────────────────────────────────┤
│ Collection Choice │ Options populated from existing Collection │
│ Set │ Use: Dynamic dropdown from variable data │
├────────────────────┼────────────────────────────────────────────────────┤
│ Record Choice Set │ Options from SOQL query built into resource │
│ │ Use: Query-based selection (e.g., Account list) │
├────────────────────┼────────────────────────────────────────────────────┤
│ Picklist Choice │ Uses standard object picklist field values │
│ Set │ Use: Industry, Stage, Status dropdowns │
├────────────────────┼────────────────────────────────────────────────────┤
│ Stage │ Progress tracking across multiple screens │
│ │ Use: Multi-screen wizards with visual progress │
│ │ Example: Identity → Configuration → Payment │
└────────────────────┴────────────────────────────────────────────────────┘
Variable Naming Conventions
| Prefix | Type | Example |
|---|---|---|
var_ |
Single variable | var_AccountName |
col_ |
Collection | col_Contacts |
rec_ |
Record variable | rec_CurrentLead |
inp_ |
Input variable | inp_RecordId |
out_ |
Output variable | out_ResultMessage |
con_ |
Constant | con_MaxRetries |
frm_ |
Formula | frm_DiscountedPrice |
Governor Limit Optimization Patterns
Pattern 1: Collection Filter vs Get Records in Loop
┌─────────────────────────────────────────────────────────────────────────┐
│ ❌ ANTI-PATTERN: Get Records Inside Loop │
└─────────────────────────────────────────────────────────────────────────┘
Loop (Accounts)
└── Get Records (Contacts WHERE AccountId = current Account)
└── ⚠️ SOQL limit: 100 queries per transaction!
┌─────────────────────────────────────────────────────────────────────────┐
│ ✅ BEST PRACTICE: Query Once + Collection Filter │
└─────────────────────────────────────────────────────────────────────────┘
Get Records (All Contacts for Account IDs in collection)
└── 1 SOQL query total
Loop (Accounts)
└── Collection Filter (Contacts WHERE AccountId = current)
└── In-memory filtering, no SOQL!
Pattern 2: Entry Criteria for Record-Triggered Flows
Always use Entry Criteria to limit when flows run:
┌─────────────────────────────────────────────────────────────────────────┐
│ Entry Criteria Examples │
├─────────────────────────────────────────────────────────────────────────┤
│ Run only when Status changes: │
│ ISNEW() || ISCHANGED({!$Record.Status}) │
├─────────────────────────────────────────────────────────────────────────┤
│ Run only for specific record types: │
│ {!$Record.RecordType.DeveloperName} = 'Enterprise' │
├─────────────────────────────────────────────────────────────────────────┤
│ Skip during data loads (bypass pattern): │
│ {!$Setup.Flow_Bypass__c.Bypass_All__c} = FALSE │
└─────────────────────────────────────────────────────────────────────────┘
Pattern 3: Transform vs Loop Decision
┌─────────────────────────────────────────────────────────────────────────┐
│ When to Use Transform vs Loop │
├───────────────────────────────┬─────────────────────────────────────────┤
│ USE TRANSFORM (30-50% faster) │ USE LOOP │
├───────────────────────────────┼─────────────────────────────────────────┤
│ Data mapping/shaping │ Per-record IF/ELSE decisions │
│ Bulk field assignments │ Counters, flags, state tracking │
│ Simple formula calculations │ Varying business rules per record │
│ Record type conversion │ Complex conditional transformations │
└───────────────────────────────┴─────────────────────────────────────────┘
See: references/transform-vs-loop-guide.md for detailed decision criteria
Before-Save vs After-Save Triggers
┌─────────────────────────────────────────────────────────────────────────┐
│ BEFORE-SAVE TRIGGER │
├─────────────────────────────────────────────────────────────────────────┤
│ When: Before record is committed to database │
│ Can modify: Trigger record only ($Record) │
│ DML needed: NO (changes auto-saved with record) │
│ Use for: │
│ • Field defaulting and auto-population │
│ • Validation and Custom Errors │
│ • Same-record field calculations │
│ • Preventing record creation (throw error) │
└─────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ AFTER-SAVE TRIGGER │
├─────────────────────────────────────────────────────────────────────────┤
│ When: After record is committed (has ID) │
│ Can modify: Related/child records, external systems │
│ DML needed: YES (explicit Create/Update/Delete required) │
│ Use for: │
│ • Creating child records │
│ • Updating parent/related records │
│ • Sending emails, notifications │
│ • HTTP callouts to external systems │
│ ⚠️ CAUTION: Updating same object can cause infinite loop! │
└─────────────────────────────────────────────────────────────────────────┘
Common Anti-Patterns to Avoid
| Anti-Pattern | Problem | Solution |
|---|---|---|
| DML in Loop | Governor limit failure | Collect records, single DML after loop |
| SOQL in Loop | Query limit exceeded | Query all data upfront, filter in memory |
| No fault paths | Silent failures | Add fault connector to all DML elements |
| No entry criteria | Runs on every update | Use ISCHANGED() or field conditions |
| After-Save same object | Infinite recursion | Add recursion check or use Before-Save |
| Hardcoded IDs | Fails in different orgs | Use Custom Metadata or Custom Labels |
| Unfiltered Get Records | Too many records | Always add filter conditions |
| Loop for field mapping | Slower processing | Use Transform element instead |
Quick Reference: Element Connectors
| Element | Connector Types |
|---|---|
| Decision | One per outcome + Default |
| Loop | nextValueConnector (each item) + noMoreValuesConnector (after last) |
| Get Records | connector (records found) + faultConnector (error) |
| Create/Update/Delete | connector (success) + faultConnector (error) |
| Screen | connector (next) |
| Wait | waitEvents with connector per condition |
Testing Checklist Quick Reference
□ Path Coverage
□ All Decision outcomes tested
□ Loop with 0, 1, many records
□ Fault paths triggered
□ Bulk Testing (Record-Triggered)
□ 1 record
□ 10 records
□ 50 records
□ 200+ records (governor limit boundary)
□ User Context
□ Standard User profile
□ Admin profile
□ FLS restrictions applied
□ Edge Cases
□ Null/empty values
□ Maximum field lengths
□ Special characters
Related Documentation
| Topic | Document |
|---|---|
| Transform vs Loop | transform-vs-loop-guide.md |
| Best Practices | flow-best-practices.md |
| Testing Guide | testing-guide.md |
| Governance | governance-checklist.md |
| Subflow Library | subflow-library.md |
| Wait Patterns | wait-patterns.md |
| LWC Integration | lwc-integration-guide.md |
Attribution
Content adapted from:
- Salesforce Ben - Flow Cheat Sheet
- Official Salesforce Documentation - Flow Builder Guide
See CREDITS.md for full attribution.
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md | Cross-ref: sf-lwc/SKILL.md -->Form Building Guide
Source: Salesforce Architect Decision Guide — Build Forms Related: flow-best-practices.md | integration-patterns.md
Overview
Salesforce offers 5 primary tools for building forms. The right choice depends on complexity, user type, testing requirements, and deployment model.
5-Tool Comparison Matrix
| Tool | Complexity | Best For | Testing | Deployment | Admin-Buildable |
|---|---|---|---|---|---|
| Dynamic Forms | Low | Single-record field visibility/layout | Manual only | Change Sets, Metadata API | Yes |
| Screen Flow | Low-Medium | Guided wizards, multi-step processes | Flow testing (CLI) | Metadata API, Change Sets | Yes |
| OmniStudio | Medium-High | Industry Cloud, complex multi-step | OmniStudio testing tools | IDX Workbench (special) | Partially |
| Screen Flow + LWC | Medium-High | Custom UI within Flow orchestration | Flow testing + Jest | Metadata API | No (developer needed) |
| LWC | High | Full custom UI, complex interactions | Jest unit tests (only option with automated testing) | Metadata API | No (developer only) |
Form Selection Decision Tree
Is the form a simple record edit (show/hide fields based on conditions)?
└── YES → Dynamic Forms
└── NO → Does the form need multi-step guided input?
└── YES → Is Industry Cloud (Health, Financial, etc.) installed?
│ └── YES → OmniStudio (if already licensed)
│ └── NO → Does it need custom UI components?
│ └── YES → Screen Flow + LWC (hybrid)
│ └── NO → Screen Flow
└── NO → Does it need complex client-side interactions?
└── YES → LWC (full custom)
└── NO → Screen Flow (simplest declarative option)
Quick Decision Table
| Need | Recommended Tool |
|---|---|
| Simple record layout with conditional visibility | Dynamic Forms |
| Guided wizard with standard components | Screen Flow |
| Multi-step form with custom input controls | Screen Flow + LWC |
| Complex real-time interactions, client-side validation | LWC |
| Industry Cloud multi-step orchestration | OmniStudio |
Dynamic Forms
Dynamic Forms replace page layouts with component-level control on Lightning record pages.
Capabilities
- Conditional visibility: Show/hide fields based on field values, user permissions, device
- Field sections: Group fields with collapsible sections
- No code: Pure configuration in Lightning App Builder
Limitations
- Single record context only — no multi-record forms
- No multi-step flows or guided processes
- Limited to record page context (no standalone forms)
- Not all standard objects supported (varies by release)
Reactive Screen Flows
Screen Flows gained reactive capabilities that enable richer form experiences.
Screen Actions (Reactive Screens)
Screen Actions allow components within a screen to communicate, enabling on-screen reactivity without advancing to the next screen.
Use cases:
- Dependent picklists across custom components
- Real-time validation feedback
- Dynamic section visibility based on input
- Auto-populating fields from a lookup selection
Transaction Boundary Warning
Each screen element breaks the transaction boundary. DML committed before a screen element cannot be rolled back after the screen. For multi-step forms with rollback needs, use the Roll Back Records element.
Screen 1: Collect input
└── Create Records (Account) ← DML COMMITS HERE
Screen 2: Collect related info
└── Create Records (Contact)
Screen 3: Confirmation
⚠️ If user navigates away at Screen 3, Account is already created but Contact may not be
Best Practice for Multi-Step Data Entry
- Collect ALL input across screens first (store in variables)
- Perform ALL DML after the final screen
- Use Fault Paths for rollback on failure
Screen Flow + LWC Hybrid
Embed custom LWC components within Screen Flow for the best of both worlds.
Architecture
Screen Flow (orchestration)
├── Screen 1: Standard flow components + Custom LWC
│ └── LWC: @api inputs ← Flow variables
│ └── LWC: FlowAttributeChangeEvent → Flow variable updates
├── Screen 2: More components
└── Screen 3: Confirmation
└── FlowNavigationFinishEvent → complete flow
When to Use
- Need custom UI (charts, maps, complex tables) within a guided process
- Admin controls the flow path; developer builds the components
- Need reactive behavior that standard flow components can't provide
Limitations
- LWC must be exposed to
lightning__FlowScreentarget - Communication between LWC and Flow uses
FlowAttributeChangeEvent(one-way push to Flow) - Cannot use Flow variables directly in LWC — must pass via
@apiproperties
LWC (Full Custom Forms)
Testing Advantage
LWC is the only form-building option with Jest unit testing. For forms requiring automated test coverage, regression testing, or CI/CD validation, LWC provides the most robust testing story.
// Jest test for a form component
describe('c-account-form', () => {
it('validates required fields before submission', () => {
const element = createElement('c-account-form', { is: AccountForm });
document.body.appendChild(element);
const submitBtn = element.shadowRoot.querySelector('lightning-button');
submitBtn.click();
return Promise.resolve().then(() => {
const errorMsg = element.shadowRoot.querySelector('.error-message');
expect(errorMsg).not.toBeNull();
});
});
});
Complexity Spectrum
Dynamic Forms < Screen Flow < Screen Flow + LWC < OmniStudio < Full LWC
(simplest) (most flexible)
Choose the simplest tool that meets requirements. Don't default to LWC when Screen Flow suffices.
Security Considerations
Experience Cloud (Community) Forms
Screen Flows on Experience Cloud run in system context by default. This means they bypass sharing rules and FLS. Explicitly enforce security:
- Add entry conditions that check the running user's access
- Use
{!$Permission.Custom_Permission}to gate access - Query with
WITH USER_MODEin any Apex Invocable Actions called from the flow - Test as a community user, not an admin
OmniStudio Security Warning
OmniStudio forms render client-side, meaning:
- Form structure and field metadata are visible in browser DevTools
- Client-side validation can be bypassed
- Always validate server-side (Before Save Flow or Apex trigger) for data integrity
Input Sanitization
Rich Text inputs in flows can contain malicious HTML/JavaScript:
- Use Before Save Flows or Apex triggers to strip unsafe HTML tags
- The
String.stripHtmlTags()Apex method removes all HTML - For selective sanitization, use a custom sanitizer that allows safe tags
OmniStudio Considerations
When to Use
- Organization is on Industry Cloud (Health Cloud, Financial Services Cloud, etc.)
- Complex, multi-step data entry with branching logic
- Need pre-built industry-specific components (e.g., care plans, financial applications)
Deployment Caveat
OmniStudio components are NOT deployable via standard Metadata API. Use IDX Workbench for deployment. OmniStudio components are also not packageable in standard managed/unmanaged packages.
This impacts:
- CI/CD pipelines (need IDX Workbench CLI integration)
- Scratch org development (manual import/export)
- ISV distribution (cannot include in AppExchange packages)
Validation Limitations by Tool
| Tool | Built-in Validation | Custom Validation | Server-Side Enforcement |
|---|---|---|---|
| Dynamic Forms | Validation Rules on object | Limited | Yes (standard validation) |
| Screen Flow | Required fields, regex on some components | Decision elements for custom logic | Before Save Flow / Trigger |
| OmniStudio | Client-side validation rules | OmniScript validation | Must add server-side separately |
| LWC | required, pattern, min/max attributes |
Full JavaScript validation | Apex controller / Before Save |
No form tool provides complete server-side validation out of the box. Always pair client-side form validation with server-side enforcement (Validation Rules, Before Save Flows, or Apex triggers).
Summary
- Start simple: Dynamic Forms for single-record layouts, Screen Flow for guided processes
- Add complexity only when needed: LWC components in Flow, or full LWC for rich interactions
- Always validate server-side: Client-side validation is a UX convenience, not a security measure
- Consider testing: If automated test coverage is required, LWC (Jest) is the strongest option
- Watch transaction boundaries: Screens break transactions in Screen Flows — plan DML placement carefully
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flow Governance Checklist
Overview
This checklist ensures that Salesforce Flows meet enterprise governance standards for security, performance, maintainability, and compliance. Use this before deploying flows to production.
Pre-Development Phase
📋 Requirements Review
- Business requirement documented with clear success criteria
- Stakeholders identified (business owner, technical owner, security reviewer)
- Scope defined (which objects, which scenarios, which users)
- Existing automation reviewed (no conflicts with other flows, process builders, workflows)
- Alternative solutions considered (Apex trigger vs Flow vs declarative field updates)
🏗️ Architecture Planning
- Orchestration pattern selected (Parent-Child, Sequential, Conditional, or standalone)
- Subflow reuse identified (can use existing subflows from library?)
- Data volume estimated (how many records will this process?)
- Governor limits reviewed (will this exceed SOQL/DML limits?)
- Integration points identified (external callouts, platform events, Apex actions)
Development Phase
💻 Technical Implementation
Naming & Organization
- Flow name follows convention:
{Type}_{Object}_{Purpose}(e.g.,RTF_Account_UpdateIndustry) - Description is clear and complete (one-sentence summary of what flow does)
- Elements have meaningful names (no "Decision_0162847" default names)
- Variables use type prefixes (
varfor single,colfor collection) - API version is current (66.0 for Spring '26)
Performance & Bulkification
- No DML inside loops (CRITICAL - causes bulk failures)
- Bulkified operations (handles collections, not single records)
- Transform element used where applicable (faster than loops for field mapping)
- Use Transform for: bulk field mapping, collection conversion, simple formulas
- Use Loop for: per-record IF/ELSE, counters/flags, varying business rules
- See
references/transform-vs-loop-guide.mdfor decision criteria - ⚠️ Create Transform in Flow Builder UI, then deploy (complex XML)
- SOQL queries minimized (get all needed data in fewest queries)
- Record lookups have appropriate filters (don't query unnecessary records)
Error Handling
- All DML operations have fault paths connected
- Fault paths connect to error logging (Sub_LogError or custom)
- Error messages are descriptive (help with troubleshooting)
- Critical failures stop execution (fail-fast pattern)
- Non-critical failures logged but don't block (fire-and-forget for notifications)
Security & Permissions
- Running mode documented (System vs User mode - why?)
- Sensitive fields identified (SSN, credit card, passwords, etc.)
- Object access documented (which objects CREATE/READ/UPDATE/DELETE)
- Field-level security considered (will users have access to all fields?)
- No hardcoded credentials or sensitive data in flow
Reusability & Maintainability
- Complex logic extracted to subflows (>200 lines suggests need for subflow)
- Subflows are single-purpose (do one thing well)
- Input/output variables clearly defined (documented with descriptions)
- Magic numbers avoided (use named constants or custom metadata)
- Auto-layout enabled (locationX/Y = 0 for cleaner diffs)
Testing Phase
🧪 Unit Testing
- Flow tested independently with representative data
- All decision paths tested (every branch, every outcome)
- Error scenarios tested (what happens when DML fails?)
- Edge cases tested (null values, empty strings, zero quantities)
- Variable values verified at each step (using debug mode)
📊 Bulk Testing
- Tested with 200+ records (Data Loader or bulk API)
- No governor limit errors (SOQL, DML, CPU time all under limits)
- Performance acceptable (<5 seconds per batch)
- Debug logs reviewed for warnings or inefficiencies
- Simulation mode passed (if using flow_simulator.py)
🔒 Security Testing
- Tested with Standard User profile (most restrictive)
- Tested with custom profiles that have limited object access
- Tested with different permission sets assigned
- Verified FLS is respected (fields without access don't cause errors)
- Verified CRUD is respected (operations without access fail gracefully)
🔗 Integration Testing
- Tested with related flows (no conflicts or race conditions)
- Tested with existing automation (Process Builder, Workflow Rules, Apex triggers)
- Tested with Apex actions (if flow calls Apex)
- Tested with external integrations (platform events, HTTP callouts)
- End-to-end user acceptance testing completed
Pre-Production Phase
📝 Documentation
- Flow documentation generated (using documentation template)
- Dependencies documented (which subflows, objects, fields are required)
- Configuration notes provided (any required custom settings, metadata)
- Rollback plan documented (how to deactivate if issues arise)
- Support documentation created (for help desk/support team)
🔍 Code Review
- Peer review completed (another developer reviewed)
- Security review completed (if accessing sensitive data)
- Architecture review completed (if complex orchestration)
- Best practices validated (all items in this checklist)
- Auto-fix recommendations applied (from enhanced_validator.py)
🚦 Deployment Preparation
- Deployment plan documented (sandbox → UAT → production)
- Change set or package created (includes all dependencies)
- Validation deployment successful (--dry-run passed)
- Activation strategy defined (deploy as Draft, activate after monitoring)
- Monitoring plan in place (how to track errors post-deployment)
Production Deployment
🚀 Deployment Day
- Backup current automation (export existing flows as reference)
- Deploy during low-traffic window (minimize user impact)
- Deploy as Draft initially (not activated until verified)
- Verify deployment successful (flow appears in Setup → Flows)
- Test basic functionality in production (with test records)
🔦 Monitoring
- Activate flow after initial verification
- Monitor error logs (Flow_Error_Log__c or debug logs)
- Monitor performance (Setup → Apex Jobs, flow interview records)
- Monitor user feedback (support tickets, user questions)
- Review after 24 hours (any unexpected behavior?)
🛠️ Post-Deployment
- Document any issues encountered during deployment
- Update documentation with production-specific notes
- Communicate to users (release notes, training, announcements)
- Schedule follow-up review (1 week, 1 month)
- Archive old automation (deactivate replaced Process Builders/Workflows)
Ongoing Maintenance
📅 Regular Reviews
- Monthly error log review (any recurring failures?)
- Quarterly performance review (execution time trends)
- Bi-annual security review (still appropriate permissions?)
- Annual architecture review (still meets business needs?)
- Update for new API versions (leverage latest features)
🔄 Change Management
- Change requests tracked (JIRA, Salesforce cases, etc.)
- Impact analysis documented (what will change affect?)
- Testing repeated for changes (full checklist for major changes)
- Version history maintained (change log in flow description)
- Deprecation plan for old flows (when will they be deactivated?)
Governance Scoring
Calculate Your Governance Score
Assign points for completed items:
- Pre-Development: 10 items × 2 points = 20 points
- Development: 25 items × 2 points = 50 points
- Testing: 15 items × 3 points = 45 points
- Pre-Production: 15 items × 3 points = 45 points
- Deployment: 10 items × 2 points = 20 points
- Ongoing: 10 items × 2 points = 20 points
Total Possible: 200 points
Governance Rating
| Score | Rating | Description |
|---|---|---|
| 180-200 | ⭐⭐⭐⭐⭐ Excellent | Enterprise-grade governance |
| 160-179 | ⭐⭐⭐⭐ Very Good | Strong governance with minor gaps |
| 140-159 | ⭐⭐⭐ Good | Acceptable governance, some improvements needed |
| 120-139 | ⭐⭐ Fair | Significant gaps, address before production |
| < 120 | ⭐ Poor | Not ready for production deployment |
Minimum for Production: 140+ (Good rating)
Exception Process
When to Request Exception
Sometimes strict governance isn't feasible. Request exception for:
- Proof-of-concept flows (not production-critical)
- Emergency hotfixes (security issues, critical bugs)
- Temporary workarounds (permanent solution in progress)
Exception Request Template
Flow Name: [Name]
Exception Requested For: [Which checklist items?]
Reason: [Why can't you comply?]
Risk Assessment: [What's the risk of proceeding?]
Mitigation Plan: [How will you reduce risk?]
Timeline: [When will full compliance be achieved?]
Approver: [Who approved this exception?]
Quick Reference Guide
Priority Checks (Must-Do)
✅ Top 5 Critical Items:
- No DML inside loops
- All DML operations have fault paths
- Tested with 200+ records (bulk testing)
- Security testing with Standard User profile
- Deployment plan and rollback documented
Common Pitfalls
❌ Top 5 Common Mistakes:
- Deploying directly to production (skip sandbox testing)
- Activating immediately after deployment (skip verification)
- No error logging (can't debug production issues)
- Not testing bulk scenarios (fails with >200 records)
- Ignoring security implications (system mode without review)
Resources
Tools
- enhanced_validator.py: Comprehensive 6-category validation (includes naming, security, performance, architecture)
- flow_simulator.py: Bulk testing simulation
Documentation
- Subflow Library: Reusable components
- Orchestration Guide: Architecture patterns
- Flow Best Practices: Security guidelines
- Architecture Review Template: Formal review process
Salesforce Resources
Version History
| Version | Date | Changes |
|---|---|---|
| 1.0 | 2024-11-30 | Initial governance checklist |
Support
Questions about this checklist?
- Review related documentation above
- Consult with Salesforce architect or admin
- Request architecture review for complex flows
Remember: Governance isn't gatekeeping—it's protecting your org from technical debt, security issues, and poor user experiences. Take the time to do it right! 🛡️
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->LWC & Apex Integration Patterns
LWC Integration (Screen Flows)
Embed custom Lightning Web Components in Flow Screens for rich, interactive UIs.
Templates
| Template | Purpose |
|---|---|
assets/screen-flow-with-lwc.xml |
Flow embedding LWC component |
assets/apex-action-template.xml |
Flow calling Apex @InvocableMethod |
Flow XML Pattern
<screens>
<fields>
<extensionName>c:recordSelector</extensionName>
<fieldType>ComponentInstance</fieldType>
<inputParameters>
<name>recordId</name>
<value><elementReference>var_RecordId</elementReference></value>
</inputParameters>
<outputParameters>
<assignToReference>var_SelectedId</assignToReference>
<name>selectedRecordId</name>
</outputParameters>
</fields>
</screens>
Documentation
| Resource | Location |
|---|---|
| LWC Integration Guide | references/lwc-integration-guide.md |
| LWC Component Setup | sf-lwc/references/flow-integration-guide.md |
| Triangle Architecture | references/triangle-pattern.md |
Apex Integration
Call Apex @InvocableMethod classes from Flow for complex business logic.
Flow XML Pattern
<actionCalls>
<name>Process_Record</name>
<actionName>RecordProcessor</actionName>
<actionType>apex</actionType>
<inputParameters>
<name>recordId</name>
<value><elementReference>var_RecordId</elementReference></value>
</inputParameters>
<outputParameters>
<assignToReference>var_IsSuccess</assignToReference>
<name>isSuccess</name>
</outputParameters>
<faultConnector>
<targetReference>Handle_Error</targetReference>
</faultConnector>
</actionCalls>
Documentation
| Resource | Location |
|---|---|
| Apex Action Template | assets/apex-action-template.xml |
| Apex @InvocableMethod Guide | sf-apex/references/flow-integration.md |
| Triangle Architecture | references/triangle-pattern.md |
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flow + LWC Integration Guide
This guide covers embedding custom Lightning Web Components in Flow Screens.
Overview
┌─────────────────────────────────────────────────────────────────────┐
│ FLOW SCREEN + LWC ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ FLOW (Screen) │ │
│ │ ┌──────────────────────────────────────────────────────┐ │ │
│ │ │ screens element │ │ │
│ │ │ ┌──────────────────────────────────────────────┐ │ │ │
│ │ │ │ fields > componentInstance │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ extensionName="c:myComponent" │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ inputParameters ────────────▶ @api (in) │ │ │ │
│ │ │ │ outputParameters ◀────────── @api (out) │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ └──────────────────────────────────────────────┘ │ │ │
│ │ └──────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Quick Reference
| Flow Element | LWC Requirement | Purpose |
|---|---|---|
extensionName |
target="lightning__FlowScreen" |
Identify LWC component |
inputParameters |
@api with role="inputOnly" |
Flow → LWC data |
outputParameters |
@api with role="outputOnly" |
LWC → Flow data |
| N/A | FlowAttributeChangeEvent |
LWC updates outputs |
| N/A | FlowNavigationFinishEvent |
LWC controls navigation |
Flow XML Structure
Basic Screen with LWC
<screens>
<name>My_LWC_Screen</name>
<label>Custom Component Screen</label>
<locationX>176</locationX>
<locationY>158</locationY>
<connector>
<targetReference>Next_Element</targetReference>
</connector>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
<fields>
<name>myLwcField</name>
<!-- Component reference: namespace:componentName -->
<extensionName>c:myFlowComponent</extensionName>
<fieldType>ComponentInstance</fieldType>
<!-- Flow → LWC (inputs) -->
<inputParameters>
<name>recordId</name>
<value>
<elementReference>var_RecordId</elementReference>
</value>
</inputParameters>
<!-- LWC → Flow (outputs) -->
<outputParameters>
<assignToReference>var_SelectedId</assignToReference>
<name>selectedRecordId</name>
</outputParameters>
</fields>
</screens>
Input Parameters
Pass data from Flow variables to LWC @api properties.
Value Types
<!-- String literal -->
<inputParameters>
<name>mode</name>
<value>
<stringValue>edit</stringValue>
</value>
</inputParameters>
<!-- Boolean literal -->
<inputParameters>
<name>showDetails</name>
<value>
<booleanValue>true</booleanValue>
</value>
</inputParameters>
<!-- Number literal -->
<inputParameters>
<name>maxRecords</name>
<value>
<numberValue>10</numberValue>
</value>
</inputParameters>
<!-- Flow variable reference -->
<inputParameters>
<name>recordId</name>
<value>
<elementReference>var_CurrentRecordId</elementReference>
</value>
</inputParameters>
<!-- Record variable (SObject) -->
<inputParameters>
<name>account</name>
<value>
<elementReference>get_Account</elementReference>
</value>
</inputParameters>
<!-- Collection variable -->
<inputParameters>
<name>selectedIds</name>
<value>
<elementReference>col_SelectedRecordIds</elementReference>
</value>
</inputParameters>
LWC Property Declaration
// LWC must declare matching @api properties
@api recordId; // Maps to inputParameter name="recordId"
@api mode; // Maps to inputParameter name="mode"
@api showDetails; // Maps to inputParameter name="showDetails"
@api maxRecords; // Maps to inputParameter name="maxRecords"
Output Parameters
Receive data from LWC @api properties into Flow variables.
Flow XML
<!-- Simple value output -->
<outputParameters>
<assignToReference>var_SelectedRecordId</assignToReference>
<name>selectedRecordId</name>
</outputParameters>
<!-- Boolean output -->
<outputParameters>
<assignToReference>var_IsComplete</assignToReference>
<name>isComplete</name>
</outputParameters>
<!-- Collection output -->
<outputParameters>
<assignToReference>col_SelectedIds</assignToReference>
<name>selectedIds</name>
</outputParameters>
LWC Dispatching Updates
CRITICAL: LWC must dispatch FlowAttributeChangeEvent for outputs to update.
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
@api selectedRecordId;
handleSelection(event) {
this.selectedRecordId = event.detail.id;
// REQUIRED: Notify Flow of the change
this.dispatchEvent(new FlowAttributeChangeEvent(
'selectedRecordId', // Property name (must match meta.xml)
this.selectedRecordId // New value
));
}
Variable Types Mapping
| Flow Type | LWC Type | XML Declaration |
|---|---|---|
String |
String |
<dataType>String</dataType> |
Number |
Number |
<dataType>Number</dataType> |
Currency |
Number |
<dataType>Currency</dataType> |
Boolean |
Boolean |
<dataType>Boolean</dataType> |
Date |
String |
<dataType>Date</dataType> |
DateTime |
String |
<dataType>DateTime</dataType> |
Record |
Object |
<objectType>Account</objectType> |
Collection |
Array |
<isCollection>true</isCollection> |
Variable Declaration Examples
<!-- String variable -->
<variables>
<name>var_SelectedId</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Boolean variable with default -->
<variables>
<name>var_IsComplete</name>
<dataType>Boolean</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
<value>
<booleanValue>false</booleanValue>
</value>
</variables>
<!-- Collection of strings -->
<variables>
<name>col_SelectedIds</name>
<dataType>String</dataType>
<isCollection>true</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Record variable -->
<variables>
<name>var_Account</name>
<dataType>SObject</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
<objectType>Account</objectType>
</variables>
Validation Patterns
Check LWC Output Before Proceeding
<screens>
<name>LWC_Screen</name>
<!-- ... -->
<connector>
<targetReference>Validate_Output</targetReference>
</connector>
</screens>
<decisions>
<name>Validate_Output</name>
<label>Validate LWC Output</label>
<defaultConnector>
<targetReference>Show_Error</targetReference>
</defaultConnector>
<defaultConnectorLabel>Invalid</defaultConnectorLabel>
<rules>
<name>Is_Valid</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>var_SelectedId</leftValueReference>
<operator>IsNull</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Continue_Flow</targetReference>
</connector>
<label>Valid Selection</label>
</rules>
</decisions>
LWC-Side Validation
@api validate() {
// Flow calls this when user clicks Next
if (!this.selectedRecordId) {
return {
isValid: false,
errorMessage: 'Please select a record before continuing.'
};
}
return { isValid: true };
}
Screen Configuration
Navigation Options
<screens>
<name>My_Screen</name>
<allowBack>true</allowBack> <!-- Show Back button -->
<allowFinish>true</allowFinish> <!-- Allow Finish (last screen) -->
<allowPause>true</allowPause> <!-- Show Pause button -->
<showFooter>true</showFooter> <!-- Show button bar -->
<showHeader>true</showHeader> <!-- Show screen label -->
</screens>
Hiding Standard Navigation
When LWC handles its own navigation:
<screens>
<name>Custom_Nav_Screen</name>
<showFooter>false</showFooter> <!-- LWC provides buttons -->
<!-- ... -->
</screens>
LWC then uses:
import { FlowNavigationFinishEvent } from 'lightning/flowSupport';
handleNext() {
this.dispatchEvent(new FlowNavigationFinishEvent('NEXT'));
}
Multiple LWCs in One Screen
<screens>
<name>Multi_LWC_Screen</name>
<label>Multiple Components</label>
<!-- First LWC -->
<fields>
<name>headerComponent</name>
<extensionName>c:flowHeader</extensionName>
<fieldType>ComponentInstance</fieldType>
<inputParameters>
<name>title</name>
<value><stringValue>Select Options</stringValue></value>
</inputParameters>
</fields>
<!-- Standard Flow field between LWCs -->
<fields>
<name>instructions</name>
<fieldText><p>Choose from the options below</p></fieldText>
<fieldType>DisplayText</fieldType>
</fields>
<!-- Second LWC -->
<fields>
<name>selectorComponent</name>
<extensionName>c:recordSelector</extensionName>
<fieldType>ComponentInstance</fieldType>
<outputParameters>
<assignToReference>var_SelectedId</assignToReference>
<name>selectedId</name>
</outputParameters>
</fields>
</screens>
Error Handling
Capture LWC Error Output
<fields>
<outputParameters>
<assignToReference>var_ErrorMessage</assignToReference>
<name>errorMessage</name>
</outputParameters>
</fields>
<!-- Check for errors after screen -->
<decisions>
<name>Check_Errors</name>
<rules>
<name>Has_Error</name>
<conditions>
<leftValueReference>var_ErrorMessage</leftValueReference>
<operator>IsNull</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Error_Handler</targetReference>
</connector>
</rules>
</decisions>
LWC Dispatching Errors
handleError(error) {
this.errorMessage = this.reduceErrors(error);
this.dispatchEvent(new FlowAttributeChangeEvent(
'errorMessage',
this.errorMessage
));
}
Context Variables
Pass Flow context to LWC using record context:
<!-- In Flow: Map $Record context -->
<inputParameters>
<name>recordId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputParameters>
<inputParameters>
<name>objectApiName</name>
<value>
<elementReference>$Record.Object</elementReference>
</value>
</inputParameters>
Templates
| Template | Use Case |
|---|---|
assets/screen-flow-with-lwc.xml |
Complete LWC screen integration |
assets/apex-action-template.xml |
Calling Apex from Flow |
Cross-Skill Integration
| Integration | See Also |
|---|---|
| LWC Component Setup | sf-lwc/references/flow-integration-guide.md |
| Full Triangle Architecture | triangle-pattern.md |
| LWC FlowAttributeChangeEvent | sf-lwc/assets/flow-screen-component/ |
Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| LWC not appearing in Flow Builder | Missing isExposed or target |
Add isExposed=true and target="lightning__FlowScreen" |
| Properties not showing in builder | Missing targetConfigs |
Add targetConfig with property definitions |
| Outputs not updating | Missing FlowAttributeChangeEvent | Dispatch event when value changes |
| Type mismatch error | Wrong dataType | Match Flow variable type to LWC property type |
| LWC not receiving inputs | Property name mismatch | Ensure name matches @api property exactly |
| Navigation not working | Wrong event type | Use FlowNavigationFinishEvent with action string |
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Multi-Step DML Rollback Pattern Example
Version: 2.0.0 Use Case: Creating related records with rollback on failure Scenario: Account → Contact → Opportunity creation with automatic cleanup
Overview
When a flow performs multiple DML operations (Create, Update, Delete), a failure in a later step can leave orphaned records from earlier successful operations. This example demonstrates the rollback pattern to maintain data integrity.
Business Scenario
A screen flow that:
- Creates an Account record
- Creates a Primary Contact for that Account
- Creates an initial Opportunity for the Account
If step 3 fails, we must delete the Contact (step 2) and Account (step 1) to prevent orphaned data.
Flow Architecture
┌─────────────────┐
│ Screen_Input │
└────────┬────────┘
│
▼
┌─────────────────┐ ┌─────────────────────┐
│ Create_Account │────▶│ Handle_Account_Error │
└────────┬────────┘ └─────────────────────┘
│ Success
▼
┌─────────────────┐ ┌─────────────────────────────┐
│ Create_Contact │────▶│ Rollback_Account_On_Error │
└────────┬────────┘ └─────────────────────────────┘
│ Success
▼
┌─────────────────────┐ ┌─────────────────────────────────┐
│ Create_Opportunity │────▶│ Rollback_Contact_And_Account │
└────────┬────────────┘ └─────────────────────────────────┘
│ Success
▼
┌─────────────────┐
│ Screen_Success │
└─────────────────┘
Variable Definitions (v2.0.0 Naming)
<!-- Input Variables -->
<variables>
<name>inp_AccountName</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>inp_ContactFirstName</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>inp_ContactLastName</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Record ID Variables (for rollback) -->
<variables>
<name>var_CreatedAccountId</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>var_CreatedContactId</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Error Tracking -->
<variables>
<name>var_ErrorMessage</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>var_ErrorStep</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Output Variables -->
<variables>
<name>out_Success</name>
<dataType>Boolean</dataType>
<isInput>false</isInput>
<isOutput>true</isOutput>
<value>
<booleanValue>false</booleanValue>
</value>
</variables>
<variables>
<name>out_ErrorDetails</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>true</isOutput>
</variables>
Step 1: Create Account
<!-- Create Account Record -->
<recordCreates>
<name>Create_Account</name>
<label>Create Account</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Store_Account_Id</targetReference>
</connector>
<faultConnector>
<targetReference>Handle_Account_Error</targetReference>
</faultConnector>
<inputAssignments>
<field>Name</field>
<value>
<elementReference>inp_AccountName</elementReference>
</value>
</inputAssignments>
<object>Account</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordCreates>
<!-- Store Account ID for potential rollback -->
<assignments>
<name>Store_Account_Id</name>
<label>Store Account Id</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>var_CreatedAccountId</assignToReference>
<operator>Assign</operator>
<value>
<elementReference>Create_Account</elementReference>
</value>
</assignmentItems>
<connector>
<targetReference>Create_Contact</targetReference>
</connector>
</assignments>
<!-- Handle Account Creation Error -->
<assignments>
<name>Handle_Account_Error</name>
<label>Handle Account Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>var_ErrorMessage</assignToReference>
<operator>Assign</operator>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>var_ErrorStep</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Account Creation</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Set_Error_Output</targetReference>
</connector>
</assignments>
Step 2: Create Contact (with Rollback on Failure)
<!-- Create Contact Record -->
<recordCreates>
<name>Create_Contact</name>
<label>Create Contact</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Store_Contact_Id</targetReference>
</connector>
<faultConnector>
<targetReference>Capture_Contact_Error</targetReference>
</faultConnector>
<inputAssignments>
<field>FirstName</field>
<value>
<elementReference>inp_ContactFirstName</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<field>LastName</field>
<value>
<elementReference>inp_ContactLastName</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<field>AccountId</field>
<value>
<elementReference>var_CreatedAccountId</elementReference>
</value>
</inputAssignments>
<object>Contact</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordCreates>
<!-- Store Contact ID for potential rollback -->
<assignments>
<name>Store_Contact_Id</name>
<label>Store Contact Id</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>var_CreatedContactId</assignToReference>
<operator>Assign</operator>
<value>
<elementReference>Create_Contact</elementReference>
</value>
</assignmentItems>
<connector>
<targetReference>Create_Opportunity</targetReference>
</connector>
</assignments>
<!-- Capture error message before rollback -->
<assignments>
<name>Capture_Contact_Error</name>
<label>Capture Contact Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>var_ErrorMessage</assignToReference>
<operator>Assign</operator>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>var_ErrorStep</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Contact Creation</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Rollback_Account</targetReference>
</connector>
</assignments>
<!-- ROLLBACK: Delete the Account we created -->
<recordDeletes>
<name>Rollback_Account</name>
<label>Rollback Account</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Set_Error_Output</targetReference>
</connector>
<faultConnector>
<!-- If rollback fails, still proceed to error output -->
<targetReference>Set_Error_Output</targetReference>
</faultConnector>
<filterLogic>and</filterLogic>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>var_CreatedAccountId</elementReference>
</value>
</filters>
<object>Account</object>
</recordDeletes>
Step 3: Create Opportunity (with Full Rollback Chain)
<!-- Create Opportunity Record -->
<recordCreates>
<name>Create_Opportunity</name>
<label>Create Opportunity</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Set_Success_Output</targetReference>
</connector>
<faultConnector>
<targetReference>Capture_Opportunity_Error</targetReference>
</faultConnector>
<inputAssignments>
<field>Name</field>
<value>
<stringValue>Initial Opportunity</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<field>AccountId</field>
<value>
<elementReference>var_CreatedAccountId</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<field>StageName</field>
<value>
<stringValue>Prospecting</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<field>CloseDate</field>
<value>
<elementReference>$Flow.CurrentDate</elementReference>
</value>
</inputAssignments>
<object>Opportunity</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordCreates>
<!-- Capture error before starting rollback chain -->
<assignments>
<name>Capture_Opportunity_Error</name>
<label>Capture Opportunity Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>var_ErrorMessage</assignToReference>
<operator>Assign</operator>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>var_ErrorStep</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Opportunity Creation</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Rollback_Contact</targetReference>
</connector>
</assignments>
<!-- ROLLBACK CHAIN: Delete Contact first -->
<recordDeletes>
<name>Rollback_Contact</name>
<label>Rollback Contact</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Rollback_Account_After_Contact</targetReference>
</connector>
<faultConnector>
<!-- Continue chain even if Contact delete fails -->
<targetReference>Rollback_Account_After_Contact</targetReference>
</faultConnector>
<filterLogic>and</filterLogic>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>var_CreatedContactId</elementReference>
</value>
</filters>
<object>Contact</object>
</recordDeletes>
<!-- ROLLBACK CHAIN: Then delete Account -->
<recordDeletes>
<name>Rollback_Account_After_Contact</name>
<label>Rollback Account After Contact</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Set_Error_Output</targetReference>
</connector>
<faultConnector>
<targetReference>Set_Error_Output</targetReference>
</faultConnector>
<filterLogic>and</filterLogic>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>var_CreatedAccountId</elementReference>
</value>
</filters>
<object>Account</object>
</recordDeletes>
Output Assignments
<!-- Success Output -->
<assignments>
<name>Set_Success_Output</name>
<label>Set Success Output</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>out_Success</assignToReference>
<operator>Assign</operator>
<value>
<booleanValue>true</booleanValue>
</value>
</assignmentItems>
<connector>
<targetReference>Screen_Success</targetReference>
</connector>
</assignments>
<!-- Error Output with Context -->
<assignments>
<name>Set_Error_Output</name>
<label>Set Error Output</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>out_Success</assignToReference>
<operator>Assign</operator>
<value>
<booleanValue>false</booleanValue>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>out_ErrorDetails</assignToReference>
<operator>Assign</operator>
<value>
<!-- Concatenate step and error for context -->
<stringValue>Failed at {!var_ErrorStep}: {!var_ErrorMessage}</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Screen_Error</targetReference>
</connector>
</assignments>
Key Patterns Demonstrated
1. Store IDs Immediately After Creation
Always capture the Id of created records in a variable so you can delete them if needed later.
2. Rollback in Reverse Order
Delete dependent records first (Contact), then parent records (Account). This respects referential integrity.
3. Continue Rollback Chain on Failure
Even if a rollback delete fails, continue to the next delete. Use fault connectors that continue the chain.
4. Capture Error Context
Store both the error message ($Flow.FaultMessage) and which step failed (var_ErrorStep) for debugging.
5. Use Output Variables
Expose out_Success and out_ErrorDetails so calling flows/processes can handle the result.
Alternative: Using the Rollback Subflow
For reusable rollback logic, use the Sub_RollbackRecords subflow:
<!-- Build collection of IDs to delete -->
<assignments>
<name>Build_Rollback_Collection</name>
<label>Build Rollback Collection</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>col_RecordsToRollback</assignToReference>
<operator>Add</operator>
<value>
<elementReference>var_CreatedContactId</elementReference>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>col_RecordsToRollback</assignToReference>
<operator>Add</operator>
<value>
<elementReference>var_CreatedAccountId</elementReference>
</value>
</assignmentItems>
</assignments>
Then call Sub_RollbackRecords with the collection. See assets/subflows/subflow-dml-rollback.xml.
Testing Checklist
- Successful creation of all 3 records
- Account failure → no orphaned records
- Contact failure → Account deleted, no Contact
- Opportunity failure → Both Contact and Account deleted
- Error messages include step context
- Works with bulk operations (200+ records)
Related Resources
- Flow Best Practices - Three-tier error handling
- Rollback Subflow Template - Reusable rollback
- Testing Guide - Comprehensive testing strategies
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Orchestration Pattern: Conditional
Overview
The Conditional pattern uses a parent flow to evaluate conditions and dynamically decide which child subflows to execute. Think of it as a smart router that directs automation down different paths based on business rules.
When to Use This Pattern
✅ Use Conditional when:
- Different scenarios require completely different logic
- You want to avoid complex branching in a single flow
- Child flows can be developed by different teams
- Business rules determine which automation to run
- You need to add new scenarios without modifying existing logic
❌ Don't use when:
- All steps must execute regardless of conditions
- Logic is simple (use inline decisions instead)
- Conditions are trivial (no need for separate subflows)
Real-World Example: Case Triage and Routing
Business Requirement
When a Case is created, route it to the appropriate team and apply appropriate automation based on priority and type:
- Priority = Critical → Escalate immediately, page on-call engineer, create Slack alert
- Priority = High + Type = Technical → Assign to senior support, create Jira ticket
- Priority = High + Type = Billing → Assign to billing team, check payment status
- Priority = Medium/Low → Standard assignment, send email notification
Each scenario has completely different logic, so we route to specialized subflows.
Architecture
Parent: RTF_Case_TriageRouter (Decision Hub)
↓
├── [Critical] → Sub_EscalateCriticalCase
│ ├── Page on-call engineer
│ ├── Create Slack alert
│ └── Assign to escalation queue
│
├── [High + Technical] → Sub_HandleTechnicalCase
│ ├── Assign to senior support
│ ├── Create Jira ticket
│ └── Set SLA timer
│
├── [High + Billing] → Sub_HandleBillingCase
│ ├── Check payment status
│ ├── Assign to billing team
│ └── Generate payment report
│
└── [Medium/Low] → Sub_HandleStandardCase
├── Auto-assign by round-robin
└── Send email notification
Implementation
Parent Flow: RTF_Case_TriageRouter
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Conditional orchestrator that routes Cases to appropriate subflows based on priority and type.</description>
<label>RTF_Case_TriageRouter</label>
<processMetadataValues>
<name>BuilderType</name>
<value>
<stringValue>LightningFlowBuilder</stringValue>
</value>
</processMetadataValues>
<processType>AutoLaunchedFlow</processType>
<!-- Routing Decision -->
<decisions>
<name>Route_By_Priority_And_Type</name>
<label>Route By Priority And Type</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnector>
<targetReference>Handle_Standard_Case</targetReference>
</defaultConnector>
<defaultConnectorLabel>Standard (Medium/Low)</defaultConnectorLabel>
<!-- Rule 1: Critical Priority -->
<rules>
<name>Critical_Priority</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>$Record.Priority</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Critical</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Escalate_Critical_Case</targetReference>
</connector>
<label>Critical</label>
</rules>
<!-- Rule 2: High Priority + Technical -->
<rules>
<name>High_Priority_Technical</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>$Record.Priority</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>High</stringValue>
</rightValue>
</conditions>
<conditions>
<leftValueReference>$Record.Type</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Technical</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Handle_Technical_Case</targetReference>
</connector>
<label>High + Technical</label>
</rules>
<!-- Rule 3: High Priority + Billing -->
<rules>
<name>High_Priority_Billing</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>$Record.Priority</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>High</stringValue>
</rightValue>
</conditions>
<conditions>
<leftValueReference>$Record.Type</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Billing</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Handle_Billing_Case</targetReference>
</connector>
<label>High + Billing</label>
</rules>
</decisions>
<!-- Subflow 1: Critical Case Escalation -->
<subflows>
<name>Escalate_Critical_Case</name>
<label>Escalate Critical Case</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_EscalateCriticalCase</flowName>
<inputAssignments>
<name>varCaseId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varCaseNumber</name>
<value>
<elementReference>$Record.CaseNumber</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varSubject</name>
<value>
<elementReference>$Record.Subject</elementReference>
</value>
</inputAssignments>
</subflows>
<!-- Subflow 2: Technical Case Handling -->
<subflows>
<name>Handle_Technical_Case</name>
<label>Handle Technical Case</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_HandleTechnicalCase</flowName>
<inputAssignments>
<name>varCaseId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varCaseNumber</name>
<value>
<elementReference>$Record.CaseNumber</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varDescription</name>
<value>
<elementReference>$Record.Description</elementReference>
</value>
</inputAssignments>
</subflows>
<!-- Subflow 3: Billing Case Handling -->
<subflows>
<name>Handle_Billing_Case</name>
<label>Handle Billing Case</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_HandleBillingCase</flowName>
<inputAssignments>
<name>varCaseId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varAccountId</name>
<value>
<elementReference>$Record.AccountId</elementReference>
</value>
</inputAssignments>
</subflows>
<!-- Subflow 4: Standard Case Handling -->
<subflows>
<name>Handle_Standard_Case</name>
<label>Handle Standard Case</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_HandleStandardCase</flowName>
<inputAssignments>
<name>varCaseId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
</subflows>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Route_By_Priority_And_Type</targetReference>
</connector>
<object>Case</object>
<recordTriggerType>Create</recordTriggerType>
<triggerType>RecordAfterSave</triggerType>
</start>
<status>Draft</status>
</Flow>
Child Flow 1: Sub_EscalateCriticalCase
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Handles critical case escalation with immediate notifications and special routing.</description>
<label>Sub_EscalateCriticalCase</label>
<processType>AutoLaunchedFlow</processType>
<!-- Step 1: Page On-Call Engineer -->
<actionCalls>
<name>Page_On_Call_Engineer</name>
<label>Page On-Call Engineer</label>
<locationX>0</locationX>
<locationY>0</locationY>
<actionName>PagerDuty_Trigger_Alert</actionName>
<actionType>apex</actionType>
<connector>
<targetReference>Create_Slack_Alert</targetReference>
</connector>
<inputParameters>
<name>caseId</name>
<value>
<elementReference>varCaseId</elementReference>
</value>
</inputParameters>
<inputParameters>
<name>urgency</name>
<value>
<stringValue>high</stringValue>
</value>
</inputParameters>
</actionCalls>
<!-- Step 2: Create Slack Alert -->
<actionCalls>
<name>Create_Slack_Alert</name>
<label>Create Slack Alert</label>
<locationX>0</locationX>
<locationY>0</locationY>
<actionName>Slack_Post_Message</actionName>
<actionType>apex</actionType>
<connector>
<targetReference>Assign_To_Escalation_Queue</targetReference>
</connector>
<inputParameters>
<name>channel</name>
<value>
<stringValue>#critical-alerts</stringValue>
</value>
</inputParameters>
<inputParameters>
<name>message</name>
<value>
<stringValue>🚨 CRITICAL CASE: {!varCaseNumber} - {!varSubject}</stringValue>
</value>
</inputParameters>
</actionCalls>
<!-- Step 3: Assign to Escalation Queue -->
<recordUpdates>
<name>Assign_To_Escalation_Queue</name>
<label>Assign To Escalation Queue</label>
<locationX>0</locationX>
<locationY>0</locationY>
<faultConnector>
<targetReference>Log_Assignment_Error</targetReference>
</faultConnector>
<filterLogic>and</filterLogic>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>varCaseId</elementReference>
</value>
</filters>
<inputAssignments>
<field>OwnerId</field>
<value>
<stringValue>00G5e000001XYZ1</stringValue><!-- Escalation Queue ID -->
</value>
</inputAssignments>
<inputAssignments>
<field>Status</field>
<value>
<stringValue>Escalated</stringValue>
</value>
</inputAssignments>
<object>Case</object>
</recordUpdates>
<!-- Error Handler -->
<subflows>
<name>Log_Assignment_Error</name>
<label>Log Assignment Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varErrorMessage</name>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>Sub_EscalateCriticalCase</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>varCaseId</elementReference>
</value>
</inputAssignments>
</subflows>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Page_On_Call_Engineer</targetReference>
</connector>
</start>
<status>Draft</status>
<!-- Input Variables -->
<variables>
<name>varCaseId</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varCaseNumber</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varSubject</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
</Flow>
Child Flow 2: Sub_HandleTechnicalCase
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Handles high-priority technical cases with Jira integration and senior support assignment.</description>
<label>Sub_HandleTechnicalCase</label>
<processType>AutoLaunchedFlow</processType>
<!-- Step 1: Create Jira Ticket -->
<actionCalls>
<name>Create_Jira_Ticket</name>
<label>Create Jira Ticket</label>
<locationX>0</locationX>
<locationY>0</locationY>
<actionName>Jira_Create_Issue</actionName>
<actionType>apex</actionType>
<connector>
<targetReference>Get_Senior_Support_Agent</targetReference>
</connector>
<inputParameters>
<name>summary</name>
<value>
<stringValue>SF Case {!varCaseNumber}</stringValue>
</value>
</inputParameters>
<inputParameters>
<name>description</name>
<value>
<elementReference>varDescription</elementReference>
</value>
</inputParameters>
<inputParameters>
<name>priority</name>
<value>
<stringValue>High</stringValue>
</value>
</inputParameters>
<storeOutputAutomatically>true</storeOutputAutomatically>
</actionCalls>
<!-- Step 2: Get Available Senior Support Agent -->
<recordLookups>
<name>Get_Senior_Support_Agent</name>
<label>Get Senior Support Agent</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
<connector>
<targetReference>Assign_To_Senior_Support</targetReference>
</connector>
<filterLogic>and</filterLogic>
<filters>
<field>IsActive</field>
<operator>EqualTo</operator>
<value>
<booleanValue>true</booleanValue>
</value>
</filters>
<filters>
<field>UserRole.Name</field>
<operator>EqualTo</operator>
<value>
<stringValue>Senior Support Engineer</stringValue>
</value>
</filters>
<getFirstRecordOnly>true</getFirstRecordOnly>
<object>User</object>
<sortField>NumberOfCasesAssigned__c</sortField>
<sortOrder>Asc</sortOrder>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordLookups>
<!-- Step 3: Assign Case -->
<recordUpdates>
<name>Assign_To_Senior_Support</name>
<label>Assign To Senior Support</label>
<locationX>0</locationX>
<locationY>0</locationY>
<filterLogic>and</filterLogic>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>varCaseId</elementReference>
</value>
</filters>
<inputAssignments>
<field>OwnerId</field>
<value>
<elementReference>Get_Senior_Support_Agent.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<field>Status</field>
<value>
<stringValue>In Progress</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<field>Jira_Ticket_Id__c</field>
<value>
<elementReference>Create_Jira_Ticket.ticketId</elementReference>
</value>
</inputAssignments>
<object>Case</object>
</recordUpdates>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Create_Jira_Ticket</targetReference>
</connector>
</start>
<status>Draft</status>
<!-- Input Variables -->
<variables>
<name>varCaseId</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varCaseNumber</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varDescription</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
</Flow>
Key Characteristics
1. Single Decision Point
All routing logic centralized in one decision element in the parent flow
2. Mutually Exclusive Paths
Only ONE child subflow executes per scenario:
If Critical → Sub_EscalateCriticalCase ONLY
If High+Tech → Sub_HandleTechnicalCase ONLY
If High+Billing → Sub_HandleBillingCase ONLY
Else → Sub_HandleStandardCase ONLY
3. Specialized Children
Each child flow is optimized for its specific scenario with unique logic
4. Easy to Extend
Add new scenarios by adding new rules and new child subflows:
<!-- Adding VIP customer handling -->
<rules>
<name>VIP_Customer</name>
<conditions>
<leftValueReference>$Record.Account.Type</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>VIP</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Handle_VIP_Case</targetReference>
</connector>
<label>VIP Customer</label>
</rules>
Benefits of Conditional Pattern
✅ Separation of Concerns
- Routing logic in parent
- Business logic in children
- No mixing of concerns
✅ Team Collaboration
- Critical escalation team owns Sub_EscalateCriticalCase
- Technical support team owns Sub_HandleTechnicalCase
- Billing team owns Sub_HandleBillingCase
- Teams work independently
✅ Simplified Testing
- Test routing logic separately from business logic
- Mock child subflows for parent testing
- Test each child independently with representative data
✅ Performance Optimization
- Only execute logic needed for the scenario
- Avoid unnecessary queries and DML
- Faster execution than "check everything" approach
✅ Maintainability
- Add new scenarios without touching existing children
- Modify specific scenario logic without affecting others
- Clear separation makes debugging easier
Common Use Cases
- Case Routing: Route by priority, type, product, geography
- Lead Assignment: Route by score, source, industry, region
- Approval Routing: Route by amount, requestor, department
- Order Fulfillment: Route by product type, shipping method, warehouse
- Error Handling: Route by error type, severity, system
Best Practices
✅ DO:
- Order Rules Carefully: Most specific conditions first, default last
- Document Decision Logic: Clear labels and descriptions
- Use Meaningful Names: Sub_Handle{Scenario}Case, not Sub_Flow1
- Keep Parent Lightweight: Only routing logic, no business logic
- Make Children Self-Contained: Each child has everything it needs
❌ DON'T:
- Duplicate Logic Across Children: Extract common logic to shared subflows
- Make Conditions Too Complex: If routing is complex, simplify business rules
- Forget the Default Path: Always have a fallback scenario
- Mix Routing and Business Logic: Keep parent as pure router
- Create Too Many Paths: >10 paths suggests need for different pattern
Advanced Pattern: Dynamic Routing
For scenarios where routing rules are stored as metadata:
<!-- Query routing rules from custom metadata -->
<recordLookups>
<name>Get_Routing_Rules</name>
<label>Get Routing Rules</label>
<object>Case_Routing_Rule__mdt</object>
<filters>
<field>IsActive__c</field>
<operator>EqualTo</operator>
<value>
<booleanValue>true</booleanValue>
</value>
</filters>
<sortField>Priority__c</sortField>
<sortOrder>Asc</sortOrder>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordLookups>
<!-- Loop through rules and evaluate -->
<loops>
<name>Evaluate_Routing_Rules</name>
<collectionReference>Get_Routing_Rules</collectionReference>
<iterationOrder>Asc</iterationOrder>
<!-- Evaluate each rule until match found -->
</loops>
Performance Considerations
Governor Limits
- DML Statements: Only the executed child's DML counts (not all children)
- SOQL Queries: Only the executed child's queries count
- Execution Time: Faster than sequential (no unnecessary steps)
Optimization Tips
- Order decision rules by frequency (most common first)
- Use indexed fields in routing conditions
- Keep routing decision fast (<100ms)
- Profile which paths execute most often
Error Handling
Each child should handle its own errors:
<!-- In each child flow -->
<recordUpdates>
<name>Some_Operation</name>
<faultConnector>
<targetReference>Log_Child_Error</targetReference>
</faultConnector>
<!-- ... -->
</recordUpdates>
<subflows>
<name>Log_Child_Error</name>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>Sub_HandleTechnicalCase</stringValue>
</value>
</inputAssignments>
<!-- ... -->
</subflows>
Related Patterns
- Parent-Child Orchestration - Execute all children
- Sequential Orchestration - Chain flows in order
- Subflow Library - Reusable components
Summary
Conditional orchestration enables smart routing where a parent flow evaluates business rules and directs execution to specialized child subflows. This pattern creates maintainable, testable automation where teams can own their scenarios independently.
Key Takeaway: If your flow has complex branching with statements like "If critical, do X, Y, Z; if high-priority technical, do A, B, C," use conditional orchestration. Each scenario becomes a focused, testable subflow. 🎯
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flow Orchestration Guide
Introduction
Flow orchestration is the practice of coordinating multiple flows to work together as a cohesive system. Instead of building large, monolithic flows, orchestration breaks complex automation into smaller, focused components that communicate through well-defined interfaces.
Why Orchestrate?
The Monolithic Flow Problem
❌ Single 800-Line Flow:
RTF_Account_Update_Everything
├── Update 5 related objects (500 lines)
├── Send 3 different notifications (100 lines)
├── Complex validation logic (150 lines)
└── Audit logging (50 lines)
Problems:
- Impossible to test individual pieces
- Changes require full regression testing
- Multiple teams can't work in parallel
- Debugging is a nightmare
- Can't reuse any logic elsewhere
The Orchestrated Approach
✅ Parent + Children (200 lines total):
RTF_Account_Update_Orchestrator (50 lines)
├── Sub_UpdateRelatedObjects (50 lines) ← Reusable!
├── Sub_SendNotifications (40 lines) ← Reusable!
├── Sub_ValidateChanges (30 lines) ← Reusable!
└── Sub_AuditLog (30 lines) ← Reusable!
Benefits:
- Test each component independently
- Change one without affecting others
- Multiple teams own their components
- Debug specific component easily
- Reuse components across flows
Three Core Orchestration Patterns
1. Parent-Child Pattern
Use when: Complex task has multiple independent responsibilities
Structure: Parent coordinates, children execute
Parent (Orchestrator)
├── Child A (does one thing)
├── Child B (does another thing)
└── Child C (does a third thing)
Example: Account industry change
- Parent: RTF_Account_IndustryChange_Orchestrator
- Child 1: Update Contacts
- Child 2: Update Opportunities
- Child 3: Send Notifications
2. Sequential Pattern
Use when: Each step depends on the previous step's output
Structure: Linear pipeline with data flowing through stages
Step 1 → Output → Step 2 → Output → Step 3 → Output → Step 4
Example: Order processing
- Step 1: Validate Order → (isValid, validationMessage)
- Step 2: Calculate Tax → (taxAmount, totalAmount)
- Step 3: Process Payment → (paymentId, status)
- Step 4: Reserve Inventory → (reservationId)
3. Conditional Pattern
Use when: Different scenarios require completely different logic
Structure: Router that directs to specialized handlers
Parent (Router)
├── [Condition A] → Handler A
├── [Condition B] → Handler B
├── [Condition C] → Handler C
└── [Default] → Handler D
Example: Case triage
- Critical → Escalate immediately
- High + Technical → Create Jira ticket
- High + Billing → Check payment status
- Standard → Auto-assign
Choosing the Right Pattern
Decision Tree
Does each step depend on the previous step's output?
├── YES → Use Sequential Pattern
│ (Order: Validate → Calculate → Charge → Fulfill)
│
└── NO → Are the steps completely independent?
├── YES → Use Parent-Child Pattern
│ (Account: Update Contacts + Update Opps + Notify)
│
└── NO → Do different scenarios need different logic?
└── YES → Use Conditional Pattern
(Case: Route by priority and type)
Pattern Comparison
| Aspect | Parent-Child | Sequential | Conditional |
|---|---|---|---|
| Execution | All children run (parallel possible) | Steps run in order | One path runs |
| Dependencies | Children independent | Each step needs previous output | Paths independent |
| Use Case | Multi-responsibility task | Multi-stage pipeline | Scenario-based routing |
| Performance | Fast (parallel possible) | Slower (sequential) | Fast (only one path) |
| Complexity | Medium | Low | Medium |
| Testability | Excellent (test each child) | Good (test each stage) | Excellent (test each path) |
Best Practices
1. Design Principles
Single Responsibility
Each flow should do ONE thing well:
✅ GOOD:
Sub_UpdateContactIndustry → Only updates Contact Industry field
❌ BAD:
Sub_UpdateEverything → Updates Contacts, Opportunities, Cases, sends emails...
Clear Interfaces
Define explicit inputs and outputs:
<!-- Good: Clear contract -->
<variables>
<name>varAccountId</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varSuccessCount</name>
<dataType>Number</dataType>
<isInput>false</isInput>
<isOutput>true</isOutput>
</variables>
Fail Fast
Check prerequisites early, fail immediately if not met:
<decisions>
<name>Check_Prerequisites</name>
<defaultConnector>
<targetReference>Log_Error_And_Exit</targetReference>
</defaultConnector>
<rules>
<name>Prerequisites_Met</name>
<!-- Only proceed if everything is ready -->
<connector>
<targetReference>Begin_Processing</targetReference>
</connector>
</rules>
</decisions>
2. Naming Conventions
Use consistent prefixes to identify orchestration roles:
| Prefix | Purpose | Example |
|---|---|---|
RTF_ |
Record-Triggered orchestrator | RTF_Account_UpdateOrchestrator |
Auto_ |
Autolaunched orchestrator | Auto_OrderProcessingPipeline |
Sub_ |
Reusable child/subflow | Sub_UpdateContactIndustry |
Screen_ |
Screen flow (UI) | Screen_OrderEntry |
Pattern: {Type}_{Object}_{Purpose}{Role}
Examples:
RTF_Account_IndustryChange_Orchestrator(parent)Sub_UpdateContactIndustry(child)Auto_ValidateOrder(sequential step)
3. Error Handling Strategy
Each Child Handles Its Own Errors
<!-- In child flow -->
<recordUpdates>
<name>Update_Records</name>
<faultConnector>
<targetReference>Log_Update_Error</targetReference>
</faultConnector>
<!-- ... -->
</recordUpdates>
<subflows>
<name>Log_Update_Error</name>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>Sub_UpdateContactIndustry</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>varAccountId</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varErrorMessage</name>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</inputAssignments>
</subflows>
Parent Monitors Overall Success
<!-- In parent flow -->
<decisions>
<name>Check_Child_Success</name>
<rules>
<name>Child_Failed</name>
<conditions>
<leftValueReference>Update_Contacts.varSuccess</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Handle_Partial_Failure</targetReference>
</connector>
</rules>
<defaultConnector>
<targetReference>Continue_To_Next_Step</targetReference>
</defaultConnector>
</decisions>
4. Performance Optimization
Minimize Subflow Calls in Loops
❌ BAD: Calling subflow 200 times
<loops>
<name>Loop_Through_Records</name>
<collectionReference>Get_Records</collectionReference>
<nextValueConnector>
<targetReference>Call_Subflow_For_Each</targetReference><!-- BAD! -->
</nextValueConnector>
</loops>
✅ GOOD: Collect, then call subflow once
<loops>
<name>Loop_Through_Records</name>
<collectionReference>Get_Records</collectionReference>
<nextValueConnector>
<targetReference>Add_To_Collection</targetReference>
</nextValueConnector>
<noMoreValuesConnector>
<targetReference>Call_Subflow_Once_With_Collection</targetReference><!-- GOOD! -->
</noMoreValuesConnector>
</loops>
Avoid Deep Nesting
✅ GOOD (3 levels):
Parent → Child → Grandchild
⚠️ WARNING (5+ levels):
Parent → Child → Grandchild → Great-grandchild → Great-great-grandchild
Limit: Maximum 50 levels (governor limit)
Recommended: Maximum 3-4 levels
Use Bulkified Operations
Each child should handle collections, not single records:
<!-- Child accepts collection -->
<variables>
<name>colRecordsToProcess</name>
<dataType>SObject</dataType>
<isCollection>true</isCollection>
<isInput>true</isInput>
</variables>
<!-- Bulk DML operation -->
<recordUpdates>
<name>Update_All_Records</name>
<inputReference>colRecordsToProcess</inputReference>
<!-- Processes entire collection in one DML -->
</recordUpdates>
Implementation Patterns
Pattern 1: Fire-and-Forget
Parent doesn't wait for children or check results:
<subflows>
<name>Send_Notification</name>
<flowName>Sub_SendEmailAlert</flowName>
<!-- No output checking, just fire it -->
<connector>
<targetReference>Next_Step</targetReference>
</connector>
</subflows>
Use when: Child failure doesn't affect parent success (e.g., non-critical notifications)
Pattern 2: Check-and-Continue
Parent checks child result, then decides:
<subflows>
<name>Validate_Data</name>
<flowName>Sub_ValidateRecord</flowName>
<storeOutputAutomatically>true</storeOutputAutomatically>
<connector>
<targetReference>Check_Validation_Result</targetReference>
</connector>
</subflows>
<decisions>
<name>Check_Validation_Result</name>
<rules>
<name>Valid</name>
<conditions>
<leftValueReference>Validate_Data.varIsValid</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<booleanValue>true</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Continue_Processing</targetReference>
</connector>
</rules>
<defaultConnector>
<targetReference>Handle_Invalid_Data</targetReference>
</defaultConnector>
</decisions>
Use when: Child result determines next step
Pattern 3: Collect-and-Report
Parent runs all children, collects results, reports summary:
<!-- Run all children -->
<subflows>
<name>Update_Contacts</name>
<flowName>Sub_UpdateContacts</flowName>
<storeOutputAutomatically>true</storeOutputAutomatically>
<connector>
<targetReference>Update_Opportunities</targetReference>
</connector>
</subflows>
<subflows>
<name>Update_Opportunities</name>
<flowName>Sub_UpdateOpportunities</flowName>
<storeOutputAutomatically>true</storeOutputAutomatically>
<connector>
<targetReference>Generate_Summary</targetReference>
</connector>
</subflows>
<!-- Collect results -->
<assignments>
<name>Generate_Summary</name>
<assignmentItems>
<assignToReference>varTotalRecordsUpdated</assignToReference>
<operator>Add</operator>
<value>
<elementReference>Update_Contacts.varRecordCount</elementReference>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>varTotalRecordsUpdated</assignToReference>
<operator>Add</operator>
<value>
<elementReference>Update_Opportunities.varRecordCount</elementReference>
</value>
</assignmentItems>
</assignments>
Use when: Parent needs to aggregate results from all children
Testing Strategy
Unit Testing Children
Test each child flow independently:
# Test Sub_UpdateContactIndustry
1. Create 200 test Contacts linked to test Account
2. Invoke Sub_UpdateContactIndustry via flow debug
3. Verify all 200 Contacts updated
4. Check no governor limit errors
5. Verify error logging if fault injected
Integration Testing Parents
Test orchestration flow end-to-end:
# Test RTF_Account_IndustryChange_Orchestrator
1. Create test Account with related Contacts, Opportunities
2. Update Account.Industry field
3. Verify all children executed
4. Check all related records updated
5. Verify notifications sent
6. Check audit logs created
Bulk Testing
Test with production-like volumes:
# Bulk test orchestrated flows
1. Use Data Loader to update 200 Accounts
2. Monitor execution in Setup → Apex Jobs
3. Check Flow_Error_Log__c for any failures
4. Verify no governor limit errors
5. Check debug logs for performance bottlenecks
Common Anti-Patterns
❌ Anti-Pattern 1: God Flow
One flow that does everything:
RTF_Account_DoEverything
├── 500 lines of Contact updates
├── 400 lines of Opportunity updates
├── 300 lines of Case updates
├── 200 lines of notification logic
└── 100 lines of audit logging
Total: 1500 lines of unmaintainable spaghetti
Fix: Break into orchestrator + specialized children
❌ Anti-Pattern 2: Circular Dependencies
Flow A calls Flow B
Flow B calls Flow C
Flow C calls Flow A ← INFINITE LOOP!
Fix: Design clear flow hierarchy with no cycles
❌ Anti-Pattern 3: Chatty Orchestration
Parent → Child A (1 record)
Parent → Child A (1 record)
Parent → Child A (1 record)
... 200 times
Total: 200 subflow calls!
Fix: Collect records, call child once with collection
❌ Anti-Pattern 4: Shared State
Flow A sets global variable
Flow B reads global variable
Flow C modifies global variable
Result: Unpredictable behavior based on execution order
Fix: Pass data explicitly via input/output variables
Troubleshooting
"Subflow not found" Error
✅ Fix:
1. Verify child flow is activated
2. Check API name matches exactly (case-sensitive)
3. Ensure child flow is deployed to target org
"Too many subflow levels" Error
✅ Fix:
1. Reduce nesting depth (max 50, recommend 3-4)
2. Flatten hierarchy by combining some children
3. Consider different orchestration pattern
Performance Issues
✅ Fix:
1. Profile flow execution in debug logs
2. Check for DML/SOQL in loops
3. Reduce number of subflow calls
4. Use Transform element instead of loops
5. Batch operations where possible
Difficult Debugging
✅ Fix:
1. Add descriptive element names
2. Use Sub_LogError in all fault paths
3. Add debug assignments to trace execution
4. Test children independently first
5. Use flow interview records to trace execution
Governor Limits
Orchestrated flows share governor limits across all components:
| Limit | Value | Orchestration Impact |
|---|---|---|
| SOQL Queries | 100 | Each child's queries count toward total |
| DML Statements | 150 | Each child's DML counts toward total |
| DML Rows | 10,000 | Shared across all children |
| CPU Time | 10,000ms | Sum of all flow execution time |
| Subflow Depth | 50 | Parent → Child → Grandchild... |
Tip: Use limits method in debug logs to monitor consumption
Version Control
Organize by Pattern
force-app/main/default/flows/
├── orchestrators/
│ ├── RTF_Account_IndustryChange_Orchestrator.flow-meta.xml
│ └── Auto_OrderProcessingPipeline.flow-meta.xml
├── subflows/
│ ├── Sub_UpdateContactIndustry.flow-meta.xml
│ ├── Sub_UpdateOpportunityStages.flow-meta.xml
│ └── Sub_SendEmailAlert.flow-meta.xml
└── standalone/
└── Screen_SimpleForm.flow-meta.xml
Dependency Documentation
Create README documenting dependencies:
# Flow Dependencies
## RTF_Account_IndustryChange_Orchestrator
- Calls: Sub_UpdateContactIndustry
- Calls: Sub_UpdateOpportunityStages
- Calls: Sub_SendEmailAlert
## Sub_UpdateContactIndustry
- No dependencies
## Sub_UpdateOpportunityStages
- Calls: Sub_LogError (error handling)
Migration Strategy
From Monolith to Orchestration
Step 1: Identify Responsibilities
Break down existing monolithic flow into distinct responsibilities
Step 2: Extract Children
Create child subflows for each responsibility
Step 3: Create Orchestrator
Build parent flow that calls children
Step 4: Test Side-by-Side
Run old and new flows in parallel (different trigger conditions)
Step 5: Cutover
Deactivate old flow, activate new orchestrated flows
Step 6: Monitor
Watch error logs and performance metrics
Success Metrics
Indicators of Good Orchestration
✅ Modularity: Average flow length < 200 lines ✅ Reusability: 40%+ of children used by multiple parents ✅ Testability: Can test each component independently ✅ Maintainability: Changes isolated to specific children ✅ Performance: No governor limit warnings ✅ Observability: Clear error logs showing which component failed
Related Documentation
- Parent-Child Pattern Example
- Sequential Pattern Example
- Conditional Pattern Example
- Subflow Library
- Error Logging Best Practices
Summary
Flow orchestration transforms complex automations from unmaintainable monoliths into modular, testable systems. By applying the three core patterns—Parent-Child, Sequential, and Conditional—you can build robust, scalable automation that's easy to understand, test, and enhance.
Key Principles:
- Single Responsibility: Each flow does one thing well
- Clear Interfaces: Explicit inputs and outputs
- Error Handling: Every component handles its own failures
- Testability: Independent testing of each component
- Reusability: Components used across multiple flows
Start small: Identify one complex flow in your org and break it into an orchestrated architecture. The benefits become immediately apparent! 🚀
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Orchestration Pattern: Parent-Child
Overview
The Parent-Child pattern is an orchestration approach where a parent flow coordinates multiple child subflows, each handling a specific responsibility. This creates modular, maintainable automation that's easier to test, debug, and enhance.
When to Use This Pattern
✅ Use Parent-Child when:
- Complex automation has multiple distinct steps
- Different teams own different parts of the logic
- You need to reuse steps across multiple parent flows
- Testing and debugging large flows is difficult
- Changes to one step shouldn't require retesting everything
❌ Don't use when:
- Automation is simple with 1-2 steps
- All logic is tightly coupled
- Performance is critical (minimal subflow overhead acceptable)
Real-World Example: Account Industry Change
Business Requirement
When an Account's Industry changes:
- Update all related Contacts with the new Industry
- Update all related Opportunities with Industry-specific Stage
- Send notification to Account Owner
- Log the change for audit purposes
❌ Monolithic Approach (Anti-Pattern)
One large flow with everything inline:
RTF_Account_IndustryChange
├── Get Related Contacts (150+ records)
├── Loop Through Contacts
│ └── Update Each Contact (DML in loop! ❌)
├── Get Related Opportunities
├── Decision: Industry = "Technology"?
│ ├── Yes → Update Stage to "Discovery"
│ └── No → Update Stage to "Qualification"
├── Loop Through Opportunities
│ └── Update Each Opportunity (DML in loop! ❌)
├── Send Email to Owner
└── Create Audit Log
Problems:
- 400+ lines of XML
- DML in loops causes bulk failures
- Can't reuse Contact update logic elsewhere
- Testing requires full end-to-end scenario
- Debugging is painful
✅ Parent-Child Approach (Best Practice)
Break into coordinated flows:
Parent: RTF_Account_IndustryChange_Orchestrator
├── Child: Sub_UpdateContactIndustry (reusable)
├── Child: Sub_UpdateOpportunityStages (reusable)
├── Child: Sub_SendEmailAlert (from library)
└── Child: Sub_CreateAuditLog (reusable)
Benefits:
- Each child is 50-100 lines
- Each child can be tested independently
- Children can be reused in other flows
- Clear separation of concerns
- Easy to add/remove steps
Implementation
Parent Flow: RTF_Account_IndustryChange_Orchestrator
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Parent orchestrator that coordinates industry change automation. Calls child subflows for each responsibility.</description>
<label>RTF_Account_IndustryChange_Orchestrator</label>
<processMetadataValues>
<name>BuilderType</name>
<value>
<stringValue>LightningFlowBuilder</stringValue>
</value>
</processMetadataValues>
<processType>AutoLaunchedFlow</processType>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Update_Contacts</targetReference>
</connector>
<object>Account</object>
<recordTriggerType>Update</recordTriggerType>
<triggerType>RecordAfterSave</triggerType>
</start>
<status>Draft</status>
<!-- Step 1: Update Related Contacts -->
<subflows>
<name>Update_Contacts</name>
<label>Update Related Contacts</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Update_Opportunities</targetReference>
</connector>
<flowName>Sub_UpdateContactIndustry</flowName>
<inputAssignments>
<name>varAccountId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varNewIndustry</name>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
</subflows>
<!-- Step 2: Update Related Opportunities -->
<subflows>
<name>Update_Opportunities</name>
<label>Update Related Opportunities</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Notify_Owner</targetReference>
</connector>
<flowName>Sub_UpdateOpportunityStages</flowName>
<inputAssignments>
<name>varAccountId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varIndustry</name>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
</subflows>
<!-- Step 3: Send Notification -->
<subflows>
<name>Notify_Owner</name>
<label>Notify Account Owner</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Create_Audit_Log</targetReference>
</connector>
<flowName>Sub_SendEmailAlert</flowName>
<inputAssignments>
<name>varEmailAddresses</name>
<value>
<elementReference>$Record.Owner.Email</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varEmailSubject</name>
<value>
<stringValue>Account Industry Updated</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varEmailBody</name>
<value>
<stringValue>Account {!$Record.Name} industry changed to {!$Record.Industry}. Related records have been updated.</stringValue>
</value>
</inputAssignments>
</subflows>
<!-- Step 4: Audit Logging -->
<subflows>
<name>Create_Audit_Log</name>
<label>Create Audit Log</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_CreateAuditLog</flowName>
<inputAssignments>
<name>varObjectName</name>
<value>
<stringValue>Account</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varFieldChanged</name>
<value>
<stringValue>Industry</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varNewValue</name>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
</subflows>
</Flow>
Child Flow 1: Sub_UpdateContactIndustry
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Updates Industry field on all Contacts related to an Account. Bulkified and reusable.</description>
<label>Sub_UpdateContactIndustry</label>
<processType>AutoLaunchedFlow</processType>
<!-- Get Related Contacts -->
<recordLookups>
<name>Get_Related_Contacts</name>
<label>Get Related Contacts</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
<connector>
<targetReference>Check_If_Contacts_Found</targetReference>
</connector>
<filterLogic>and</filterLogic>
<filters>
<field>AccountId</field>
<operator>EqualTo</operator>
<value>
<elementReference>varAccountId</elementReference>
</value>
</filters>
<getFirstRecordOnly>false</getFirstRecordOnly>
<object>Contact</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordLookups>
<!-- Decision: Were contacts found? -->
<decisions>
<name>Check_If_Contacts_Found</name>
<label>Contacts Found?</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnectorLabel>No Contacts</defaultConnectorLabel>
<rules>
<name>Contacts_Exist</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>Get_Related_Contacts</leftValueReference>
<operator>IsNull</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Update_Contacts_Bulk</targetReference>
</connector>
<label>Contacts Exist</label>
</rules>
</decisions>
<!-- Bulk Update (NO DML in loops!) -->
<recordUpdates>
<name>Update_Contacts_Bulk</name>
<label>Update Contacts (Bulk)</label>
<locationX>0</locationX>
<locationY>0</locationY>
<faultConnector>
<targetReference>Log_Update_Error</targetReference>
</faultConnector>
<inputAssignments>
<field>Industry</field>
<value>
<elementReference>varNewIndustry</elementReference>
</value>
</inputAssignments>
<inputReference>Get_Related_Contacts</inputReference>
</recordUpdates>
<!-- Error Handler -->
<subflows>
<name>Log_Update_Error</name>
<label>Log Update Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varErrorMessage</name>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>Sub_UpdateContactIndustry</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>varAccountId</elementReference>
</value>
</inputAssignments>
</subflows>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Get_Related_Contacts</targetReference>
</connector>
</start>
<status>Draft</status>
<!-- Input Variables -->
<variables>
<name>varAccountId</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varNewIndustry</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
</Flow>
Child Flow 2: Sub_UpdateOpportunityStages
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Updates Opportunity Stages based on Industry. Demonstrates conditional logic in child flows.</description>
<label>Sub_UpdateOpportunityStages</label>
<processType>AutoLaunchedFlow</processType>
<!-- Get Related Opportunities -->
<recordLookups>
<name>Get_Related_Opportunities</name>
<label>Get Related Opportunities</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
<connector>
<targetReference>Check_If_Opportunities_Found</targetReference>
</connector>
<filterLogic>and</filterLogic>
<filters>
<field>AccountId</field>
<operator>EqualTo</operator>
<value>
<elementReference>varAccountId</elementReference>
</value>
</filters>
<filters>
<field>IsClosed</field>
<operator>EqualTo</operator>
<value>
<booleanValue>false</booleanValue>
</value>
</filters>
<getFirstRecordOnly>false</getFirstRecordOnly>
<object>Opportunity</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordLookups>
<!-- Decision: Were opportunities found? -->
<decisions>
<name>Check_If_Opportunities_Found</name>
<label>Opportunities Found?</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnectorLabel>No Opportunities</defaultConnectorLabel>
<rules>
<name>Opportunities_Exist</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>Get_Related_Opportunities</leftValueReference>
<operator>IsNull</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Determine_Stage_By_Industry</targetReference>
</connector>
<label>Opportunities Exist</label>
</rules>
</decisions>
<!-- Decision: Which stage based on Industry? -->
<decisions>
<name>Determine_Stage_By_Industry</name>
<label>Determine Stage By Industry</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnector>
<targetReference>Set_Default_Stage</targetReference>
</defaultConnector>
<defaultConnectorLabel>Other Industries</defaultConnectorLabel>
<rules>
<name>Technology_Industry</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>varIndustry</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Technology</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Set_Technology_Stage</targetReference>
</connector>
<label>Technology</label>
</rules>
<rules>
<name>Healthcare_Industry</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>varIndustry</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Healthcare</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Set_Healthcare_Stage</targetReference>
</connector>
<label>Healthcare</label>
</rules>
</decisions>
<!-- Assignment: Technology Stage -->
<assignments>
<name>Set_Technology_Stage</name>
<label>Set Technology Stage</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>varNewStage</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Discovery</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Update_Opportunity_Stages</targetReference>
</connector>
</assignments>
<!-- Assignment: Healthcare Stage -->
<assignments>
<name>Set_Healthcare_Stage</name>
<label>Set Healthcare Stage</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>varNewStage</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Needs Analysis</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Update_Opportunity_Stages</targetReference>
</connector>
</assignments>
<!-- Assignment: Default Stage -->
<assignments>
<name>Set_Default_Stage</name>
<label>Set Default Stage</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>varNewStage</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Qualification</stringValue>
</value>
</assignmentItems>
<connector>
<targetReference>Update_Opportunity_Stages</targetReference>
</connector>
</assignments>
<!-- Bulk Update Opportunities -->
<recordUpdates>
<name>Update_Opportunity_Stages</name>
<label>Update Opportunity Stages</label>
<locationX>0</locationX>
<locationY>0</locationY>
<faultConnector>
<targetReference>Log_Update_Error</targetReference>
</faultConnector>
<inputAssignments>
<field>StageName</field>
<value>
<elementReference>varNewStage</elementReference>
</value>
</inputAssignments>
<inputReference>Get_Related_Opportunities</inputReference>
</recordUpdates>
<!-- Error Handler -->
<subflows>
<name>Log_Update_Error</name>
<label>Log Update Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varErrorMessage</name>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>Sub_UpdateOpportunityStages</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>varAccountId</elementReference>
</value>
</inputAssignments>
</subflows>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Get_Related_Opportunities</targetReference>
</connector>
</start>
<status>Draft</status>
<!-- Variables -->
<variables>
<name>varAccountId</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varIndustry</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varNewStage</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
</Flow>
Benefits of This Pattern
1. Modularity
Each child flow has one clear responsibility:
- Sub_UpdateContactIndustry: Only handles Contact updates
- Sub_UpdateOpportunityStages: Only handles Opportunity logic
- Sub_SendEmailAlert: Only handles notifications
2. Reusability
Child flows can be called from multiple parents:
RTF_Account_IndustryChange → Sub_UpdateContactIndustry
RTF_Account_Merge → Sub_UpdateContactIndustry
Auto_BulkIndustryUpdate → Sub_UpdateContactIndustry
3. Testability
Test each child independently:
- Unit test: Sub_UpdateContactIndustry with 200 Contacts
- Unit test: Sub_UpdateOpportunityStages with various Industries
- Integration test: Parent flow with full scenario
4. Maintainability
Update logic in one place:
- Need to change Contact update logic? Edit Sub_UpdateContactIndustry
- All parent flows automatically get the update
- No need to find/replace across multiple flows
5. Debugging
Clear error isolation:
- Error in Contact update? Check Sub_UpdateContactIndustry logs
- Parent flow shows which step failed
- Error logs show exact subflow name
Performance Considerations
Governor Limits
- Subflow Depth: Max 50 levels (parent → child → grandchild...)
- DML Statements: Each child's DML counts toward 150 limit
- SOQL Queries: Each child's query counts toward 100 limit
Best Practices
✅ Keep parent flow lightweight (orchestration only) ✅ Put complex logic in children ✅ Use bulkified operations in each child ✅ Monitor total DML/SOQL across all children
Testing Strategy
1. Unit Test Each Child
# Test Sub_UpdateContactIndustry
Create 200 test Contacts → Manually invoke flow → Verify all updated
2. Integration Test Parent
# Test full orchestration
Update Account Industry → Verify all children executed → Check audit logs
3. Bulk Test
# Test with 200+ Accounts
Data Loader update 200 Accounts → Verify no governor limit errors
When to Add More Children
Add a new child subflow when:
- New requirement emerges (e.g., "Also update Cases")
- Existing child gets too complex (>200 lines)
- You need to reuse logic elsewhere
<!-- Adding a new step is easy -->
<subflows>
<name>Update_Cases</name>
<label>Update Related Cases</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Notify_Owner</targetReference>
</connector>
<flowName>Sub_UpdateCaseIndustry</flowName>
<inputAssignments>
<name>varAccountId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varIndustry</name>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
</subflows>
Related Patterns
- Sequential Orchestration - Chain flows A → B → C
- Conditional Orchestration - Parent decides which children to call
- Subflow Library - Reusable subflow templates
Summary
Parent-Child orchestration transforms complex automations from monolithic nightmares into modular, maintainable architectures. Each child flow is focused, testable, and reusable—making your entire automation ecosystem more robust.
Key Takeaway: If your flow has more than 3 distinct responsibilities, consider breaking it into a parent orchestrator with child subflows. Your future self (and your team) will thank you! 🚀
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Orchestration Pattern: Sequential
Overview
The Sequential pattern chains multiple flows together where each flow's output becomes the next flow's input. This creates a pipeline of transformations, with each step building on the previous one.
When to Use This Pattern
✅ Use Sequential when:
- Each step depends on the previous step's output
- You need a multi-stage validation/approval process
- Data flows through a transformation pipeline
- Steps must execute in a specific order
- Each stage can be developed and tested independently
❌ Don't use when:
- Steps are independent and can run in parallel
- Order doesn't matter
- You need conditional branching (use Conditional pattern instead)
Real-World Example: Order Processing Pipeline
Business Requirement
Process customer orders through multiple stages:
- Validate Order: Check inventory, pricing, customer credit
- Calculate Tax: Determine tax based on shipping address and products
- Process Payment: Charge payment method
- Reserve Inventory: Allocate products from warehouse
- Generate Invoice: Create invoice record and send to customer
Each step depends on the previous step's success. If any step fails, the pipeline stops.
Architecture
Screen Flow: Order_Entry
↓ (User submits order)
Auto Flow: Auto_ValidateOrder
↓ (Outputs: varIsValid, varValidationMessage)
Auto Flow: Auto_CalculateTax
↓ (Outputs: varTaxAmount, varTotalAmount)
Auto Flow: Auto_ProcessPayment
↓ (Outputs: varPaymentId, varPaymentStatus)
Auto Flow: Auto_ReserveInventory
↓ (Outputs: varReservationId)
Auto Flow: Auto_GenerateInvoice
↓ (Outputs: varInvoiceId)
Screen Flow: Order_Confirmation (displays final results)
Implementation
Flow 1: Screen_OrderEntry
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>Entry point for order processing. Collects order details and initiates sequential pipeline.</description>
<label>Screen_OrderEntry</label>
<processType>Flow</processType>
<!-- Screen: Collect Order Information -->
<screens>
<name>Order_Details_Screen</name>
<label>Enter Order Details</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>true</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<connector>
<targetReference>Validate_Order</targetReference>
</connector>
<fields>
<name>ProductId</name>
<dataType>String</dataType>
<fieldText>Product</fieldText>
<fieldType>InputField</fieldType>
<isRequired>true</isRequired>
</fields>
<fields>
<name>Quantity</name>
<dataType>Number</dataType>
<fieldText>Quantity</fieldText>
<fieldType>InputField</fieldType>
<isRequired>true</isRequired>
<scale>0</scale>
</fields>
<fields>
<name>ShippingAddress</name>
<dataType>String</dataType>
<fieldText>Shipping Address</fieldText>
<fieldType>LargeTextArea</fieldType>
<isRequired>true</isRequired>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
<!-- Step 1: Validate Order -->
<subflows>
<name>Validate_Order</name>
<label>Validate Order</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Check_Validation_Result</targetReference>
</connector>
<flowName>Auto_ValidateOrder</flowName>
<inputAssignments>
<name>varProductId</name>
<value>
<elementReference>ProductId</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varQuantity</name>
<value>
<elementReference>Quantity</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Decision: Did validation pass? -->
<decisions>
<name>Check_Validation_Result</name>
<label>Validation Passed?</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnector>
<targetReference>Show_Validation_Error</targetReference>
</defaultConnector>
<defaultConnectorLabel>Failed</defaultConnectorLabel>
<rules>
<name>Validation_Passed</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>Validate_Order.varIsValid</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<booleanValue>true</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Calculate_Tax</targetReference>
</connector>
<label>Passed</label>
</rules>
</decisions>
<!-- Step 2: Calculate Tax (only if validation passed) -->
<subflows>
<name>Calculate_Tax</name>
<label>Calculate Tax</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Process_Payment</targetReference>
</connector>
<flowName>Auto_CalculateTax</flowName>
<inputAssignments>
<name>varProductId</name>
<value>
<elementReference>ProductId</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varQuantity</name>
<value>
<elementReference>Quantity</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varShippingAddress</name>
<value>
<elementReference>ShippingAddress</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Step 3: Process Payment (uses tax calculation output) -->
<subflows>
<name>Process_Payment</name>
<label>Process Payment</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Check_Payment_Result</targetReference>
</connector>
<flowName>Auto_ProcessPayment</flowName>
<inputAssignments>
<name>varTotalAmount</name>
<value>
<elementReference>Calculate_Tax.varTotalAmount</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Decision: Did payment succeed? -->
<decisions>
<name>Check_Payment_Result</name>
<label>Payment Successful?</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnector>
<targetReference>Show_Payment_Error</targetReference>
</defaultConnector>
<defaultConnectorLabel>Failed</defaultConnectorLabel>
<rules>
<name>Payment_Successful</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>Process_Payment.varPaymentStatus</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Success</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Reserve_Inventory</targetReference>
</connector>
<label>Success</label>
</rules>
</decisions>
<!-- Step 4: Reserve Inventory (only after successful payment) -->
<subflows>
<name>Reserve_Inventory</name>
<label>Reserve Inventory</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Generate_Invoice</targetReference>
</connector>
<flowName>Auto_ReserveInventory</flowName>
<inputAssignments>
<name>varProductId</name>
<value>
<elementReference>ProductId</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varQuantity</name>
<value>
<elementReference>Quantity</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Step 5: Generate Invoice (final step) -->
<subflows>
<name>Generate_Invoice</name>
<label>Generate Invoice</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Show_Confirmation</targetReference>
</connector>
<flowName>Auto_GenerateInvoice</flowName>
<inputAssignments>
<name>varProductId</name>
<value>
<elementReference>ProductId</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varQuantity</name>
<value>
<elementReference>Quantity</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varTaxAmount</name>
<value>
<elementReference>Calculate_Tax.varTaxAmount</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varTotalAmount</name>
<value>
<elementReference>Calculate_Tax.varTotalAmount</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varPaymentId</name>
<value>
<elementReference>Process_Payment.varPaymentId</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Success Screen -->
<screens>
<name>Show_Confirmation</name>
<label>Order Confirmation</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>false</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<fields>
<name>ConfirmationMessage</name>
<fieldText>Order Successful! Invoice #{!Generate_Invoice.varInvoiceNumber} has been created.</fieldText>
<fieldType>DisplayText</fieldType>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
<!-- Error Screens -->
<screens>
<name>Show_Validation_Error</name>
<label>Validation Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>true</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<fields>
<name>ValidationErrorMessage</name>
<fieldText>Order validation failed: {!Validate_Order.varValidationMessage}</fieldText>
<fieldType>DisplayText</fieldType>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
<screens>
<name>Show_Payment_Error</name>
<label>Payment Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>false</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<fields>
<name>PaymentErrorMessage</name>
<fieldText>Payment failed. Your order has not been processed.</fieldText>
<fieldType>DisplayText</fieldType>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Order_Details_Screen</targetReference>
</connector>
</start>
<status>Draft</status>
</Flow>
Flow 2: Auto_ValidateOrder
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<description>First step in sequential pipeline. Validates order details and returns validation status.</description>
<label>Auto_ValidateOrder</label>
<processType>AutoLaunchedFlow</processType>
<!-- Query Product for Availability Check -->
<recordLookups>
<name>Get_Product_Details</name>
<label>Get Product Details</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
<connector>
<targetReference>Check_Product_Found</targetReference>
</connector>
<filterLogic>and</filterLogic>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>varProductId</elementReference>
</value>
</filters>
<getFirstRecordOnly>true</getFirstRecordOnly>
<object>Product2</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordLookups>
<!-- Validation Logic -->
<decisions>
<name>Check_Product_Found</name>
<label>Product Exists?</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnector>
<targetReference>Set_Invalid_Product</targetReference>
</defaultConnector>
<defaultConnectorLabel>Not Found</defaultConnectorLabel>
<rules>
<name>Product_Exists</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>Get_Product_Details</leftValueReference>
<operator>IsNull</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Check_Quantity</targetReference>
</connector>
<label>Exists</label>
</rules>
</decisions>
<decisions>
<name>Check_Quantity</name>
<label>Quantity Valid?</label>
<locationX>0</locationX>
<locationY>0</locationY>
<defaultConnector>
<targetReference>Set_Invalid_Quantity</targetReference>
</defaultConnector>
<defaultConnectorLabel>Invalid</defaultConnectorLabel>
<rules>
<name>Quantity_Valid</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>varQuantity</leftValueReference>
<operator>GreaterThan</operator>
<rightValue>
<numberValue>0.0</numberValue>
</rightValue>
</conditions>
<connector>
<targetReference>Set_Valid</targetReference>
</connector>
<label>Valid</label>
</rules>
</decisions>
<!-- Set Validation Results -->
<assignments>
<name>Set_Valid</name>
<label>Set Valid</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>varIsValid</assignToReference>
<operator>Assign</operator>
<value>
<booleanValue>true</booleanValue>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>varValidationMessage</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Validation passed</stringValue>
</value>
</assignmentItems>
</assignments>
<assignments>
<name>Set_Invalid_Product</name>
<label>Set Invalid Product</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>varIsValid</assignToReference>
<operator>Assign</operator>
<value>
<booleanValue>false</booleanValue>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>varValidationMessage</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Product not found</stringValue>
</value>
</assignmentItems>
</assignments>
<assignments>
<name>Set_Invalid_Quantity</name>
<label>Set Invalid Quantity</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>varIsValid</assignToReference>
<operator>Assign</operator>
<value>
<booleanValue>false</booleanValue>
</value>
</assignmentItems>
<assignmentItems>
<assignToReference>varValidationMessage</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Quantity must be greater than 0</stringValue>
</value>
</assignmentItems>
</assignments>
<start>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Get_Product_Details</targetReference>
</connector>
</start>
<status>Draft</status>
<!-- Input Variables -->
<variables>
<name>varProductId</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>varQuantity</name>
<dataType>Number</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
<scale>0</scale>
</variables>
<!-- Output Variables -->
<variables>
<name>varIsValid</name>
<dataType>Boolean</dataType>
<isInput>false</isInput>
<isOutput>true</isOutput>
<value>
<booleanValue>false</booleanValue>
</value>
</variables>
<variables>
<name>varValidationMessage</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>true</isOutput>
</variables>
</Flow>
Key Characteristics
1. Linear Flow
Each step executes only after the previous step completes:
Step 1 → Output → Step 2 → Output → Step 3 → Output → Step 4
2. Data Propagation
Outputs from earlier steps are passed as inputs to later steps:
Calculate_Tax.varTotalAmount → Process_Payment.varTotalAmount
Process_Payment.varPaymentId → Generate_Invoice.varPaymentId
3. Fail-Fast Behavior
If any step fails, the pipeline stops:
Validation Failed → Show Error → End (no further processing)
Payment Failed → Show Error → End (inventory not reserved)
4. Clear Exit Points
Each validation point can terminate the flow early, preventing unnecessary work.
Benefits of Sequential Pattern
✅ Staged Processing
- Break complex workflows into digestible stages
- Each stage has clear inputs and outputs
- Easy to understand flow of data
✅ Error Isolation
- Know exactly which stage failed
- Can retry individual stages
- Log shows precise failure point
✅ Flexibility
- Add new stages easily
- Remove stages without affecting others
- Reorder stages if dependencies allow
✅ Testing
- Test each stage independently
- Mock outputs for downstream testing
- Verify data transformation at each step
Common Use Cases
- Order Processing: Validate → Calculate → Charge → Fulfill → Invoice
- Approval Workflows: Submit → Manager Approval → Director Approval → Execute
- Data Transformation: Extract → Transform → Validate → Load
- Document Generation: Gather Data → Apply Template → Generate PDF → Send
- Multi-Step Validation: Check A → Check B → Check C → Approve
Best Practices
✅ DO:
- Define Clear Contracts: Each flow should have well-defined inputs and outputs
- Use Output Variables: Pass data between stages via output variables
- Validate at Each Stage: Check prerequisites before expensive operations
- Log Stage Completion: Track which stages completed successfully
- Design for Rollback: Consider how to undo if later stages fail
❌ DON'T:
- Create Circular Dependencies: A → B → C → A (infinite loop!)
- Skip Error Handling: Every stage should have fault paths
- Make Steps Too Large: Each stage should do ONE thing well
- Ignore Performance: Sequential = slower than parallel (by design)
- Hardcode Values: Use variables to pass data between stages
Performance Considerations
Sequential = Longer Execution Time
Parallel (3 seconds total):
Step A (1s) ───┐
Step B (1s) ───┼──→ Complete
Step C (1s) ───┘
Sequential (3 seconds total):
Step A (1s) → Step B (1s) → Step C (1s) → Complete
Trade-off: Sequential is slower but provides:
- Better error handling
- Clear data flow
- Easier debugging
- Predictable execution order
Error Handling in Pipelines
Strategy 1: Fail Fast
Stop on first error (shown in example above)
Strategy 2: Collect and Report
Continue through all steps, collect all errors, report at end:
<!-- Track errors but don't stop -->
<assignments>
<name>Add_To_Error_List</name>
<assignmentItems>
<assignToReference>colErrors</assignToReference>
<operator>Add</operator>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</assignmentItems>
<connector>
<targetReference>Next_Step</targetReference>
</connector>
</assignments>
Strategy 3: Retry Logic
Attempt failed step again before failing:
<decisions>
<name>Check_Retry_Count</name>
<rules>
<name>Can_Retry</name>
<conditions>
<leftValueReference>varRetryCount</leftValueReference>
<operator>LessThan</operator>
<rightValue>
<numberValue>3.0</numberValue>
</rightValue>
</conditions>
<connector>
<targetReference>Increment_Retry</targetReference>
</connector>
</rules>
<defaultConnector>
<targetReference>Report_Failure</targetReference>
</defaultConnector>
</decisions>
Related Patterns
- Parent-Child Orchestration - Coordinate parallel operations
- Conditional Orchestration - Branch based on conditions
- Subflow Library - Reusable building blocks
Summary
Sequential orchestration creates clear, predictable workflows where each step builds on the previous one. While slower than parallel execution, the benefits of clear data flow, error isolation, and maintainability make it ideal for multi-stage processes with dependencies.
Key Takeaway: If your workflow is "Step A must complete before Step B can start," use sequential orchestration. Each stage becomes a tested, reusable component in your automation pipeline. 🔗
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Multi-Skill Orchestration: sf-flow Perspective
This document details how sf-flow fits into the multi-skill workflow for Salesforce development.
Standard Orchestration Order
┌─────────────────────────────────────────────────────────────────────────────┐
│ STANDARD MULTI-SKILL ORCHESTRATION ORDER │
├─────────────────────────────────────────────────────────────────────────────┤
│ 1. sf-metadata │
│ └── Create object/field definitions (LOCAL files) │
│ │
│ 2. sf-flow ◀── YOU ARE HERE │
│ └── Create flow definitions (LOCAL files) │
│ │
│ 3. sf-deploy │
│ └── Deploy all metadata (REMOTE) │
│ │
│ 4. sf-data │
│ └── Create test data (REMOTE - objects must exist!) │
└─────────────────────────────────────────────────────────────────────────────┘
Why sf-flow Depends on sf-metadata
| sf-flow Uses | From sf-metadata | What Fails Without It |
|---|---|---|
| Object references | Custom Objects | Invalid reference: Quote__c |
| Field references | Custom Fields | Field does not exist: Status__c |
| Picklist values | Picklist Fields | Flow decision uses non-existent value |
| Record Types | Record Type metadata | Invalid record type: Inquiry |
Rule: If your Flow references custom objects or fields, create them with sf-metadata FIRST.
sf-flow's Role in the Triangle Architecture
Flow acts as the orchestrator in the Flow-LWC-Apex triangle:
┌─────────────────────┐
│ FLOW │◀── YOU ARE HERE
│ (Orchestrator) │
└──────────┬──────────┘
│
┌─────────────────────┼─────────────────────┐
│ │ │
▼ ▼ │
┌─────────────────┐ ┌─────────────────┐ │
│ LWC Screen │ │ Apex Invocable │ │
│ Component │ │ Action │ │
└────────┬────────┘ └────────┬────────┘ │
│ @AuraEnabled │ │
└──────────┬──────────┘ │
▼ │
┌─────────────────────┐ │
│ Apex Controller │─────────────────────┘
└─────────────────────┘ Results back to Flow
See references/triangle-pattern.md for detailed Flow XML patterns.
Integration + Agentforce Extended Order
When building agents with Flow actions:
┌─────────────────────────────────────────────────────────────────────────────┐
│ AGENTFORCE FLOW ORCHESTRATION │
├─────────────────────────────────────────────────────────────────────────────┤
│ 1. sf-metadata │
│ └── Create object/field definitions │
│ │
│ 2. sf-connected-apps (if external API) │
│ └── Create OAuth Connected App │
│ │
│ 3. sf-integration (if external API) │
│ └── Create Named Credential + External Service │
│ │
│ 4. sf-apex (if custom logic needed) │
│ └── Create @InvocableMethod classes │
│ │
│ 5. sf-flow ◀── YOU ARE HERE │
│ └── Create Flow (HTTP Callout, Apex wrapper, or standard) │
│ │
│ 6. sf-deploy │
│ └── Deploy all metadata │
│ │
│ 7. sf-ai-agentforce │
│ └── Create agent with flow:// target │
│ │
│ 8. sf-deploy │
│ └── Publish agent (sf agent publish authoring-bundle) │
└─────────────────────────────────────────────────────────────────────────────┘
Flows for Agentforce: Critical Requirements
When creating Flows that will be called by Agentforce agents:
1. Variable Name Matching
Agent Script input/output names MUST match Flow variable API names exactly:
<!-- Flow variable -->
<variables>
<name>inp_AccountId</name>
<dataType>String</dataType>
<isInput>true</isInput>
</variables>
# Agent Script action - names must match!
actions:
- name: GetAccountDetails
target: flow://Get_Account_Details
inputs:
- name: inp_AccountId # Must match Flow variable name
source: slot
2. Flow Requirements for Agents
| Requirement | Why |
|---|---|
| Autolaunched or Screen Flow | Record-triggered flows cannot be called directly |
isInput: true for inputs |
Agent needs to pass values |
isOutput: true for outputs |
Agent needs to read results |
| Descriptive variable names | Agent uses these in responses |
3. Common Integration Errors
| Error | Cause | Fix |
|---|---|---|
| "Internal Error" on publish | Variable name mismatch | Match Flow var names exactly |
| "Flow not found" | Flow not deployed | sf-deploy before sf-ai-agentforce |
| Agent can't read output | Missing isOutput: true |
Add output flag to Flow variable |
Cross-Skill Integration Table
| From Skill | To sf-flow | When |
|---|---|---|
| sf-ai-agentforce | → sf-flow | "Create Autolaunched Flow for agent action" |
| sf-apex | → sf-flow | "Create Flow wrapper for Apex logic" |
| sf-integration | → sf-flow | "Create HTTP Callout Flow" |
| From sf-flow | To Skill | When |
|---|---|---|
| sf-flow | → sf-metadata | "Describe Invoice__c" (verify fields before flow) |
| sf-flow | → sf-deploy | "Deploy flow with --dry-run" |
| sf-flow | → sf-data | "Create 200 test Accounts" (after deploy) |
Deployment Order for Flow Dependencies
When deploying Flows that reference Apex or LWC:
1. APEX CLASSES (if @InvocableMethod called)
└── Deploy first
2. LWC COMPONENTS (if used in Screen Flow)
└── Deploy second
3. FLOWS ◀── Deploy LAST
└── References deployed Apex/LWC
Best Practices
- Always verify objects exist before creating Flow references
- Use sf-metadata describe to confirm field API names
- Deploy as Draft first for complex flows
- Test with 251 records for bulk safety
- Match variable names exactly when creating for Agentforce
Related Documentation
| Topic | Location |
|---|---|
| Triangle pattern (Flow perspective) | sf-flow/references/triangle-pattern.md |
| LWC integration | sf-flow/references/lwc-integration-guide.md |
| Apex action template | sf-flow/assets/apex-action-template.xml |
| sf-ai-agentforce | sf-ai-agentforce/SKILL.md |
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Record-Triggered Flow Example: Opportunity Stage Update
This example demonstrates creating a Record-Triggered Flow with proper bulkification that updates related contacts when an Opportunity reaches "Closed Won".
Scenario
When an Opportunity is marked as "Closed Won":
- Find all related Contacts
- Update their Status__c field to "Customer"
- Send notification to account owner
- Handle bulk updates (200+ opportunities at once)
User Request
User: "Create a record-triggered flow on Opportunity.
When the Stage changes to 'Closed Won', update all related contacts
to have Status__c = 'Customer'."
Skill Workflow
Phase 1: Requirements Gathering
The skill asks:
Q1: What type of flow? → Record-Triggered Flow (After-Save)
Q2: What is the purpose? → "Update related contacts when opportunity reaches Closed Won"
Q3: Which object triggers this flow? → "Opportunity"
Q4: When should it run? → After records are created OR updated
Q5: Target org? → "production" (careful - always test in sandbox first!)
Phase 2: Flow Design
The skill designs a bulkified flow:
- Trigger: Opportunity, After Save, Create and Update
- bulkSupport: true (CRITICAL for bulk processing)
- Decision: Check if Stage = 'Closed Won'
- Get Records: Related Contacts (collection)
- Update Records: Contact collection (single DML, outside any loops)
- Fault Path: Error handling for DML failure
Phase 3: Validation
Flow Validation Report: Opportunity_Closed_Won_Update_Contacts (API 66.0)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ XML Structure: Valid
✓ API Version: 66.0 (current - Spring '26)
✓ Required Elements: Present
✓ Element References: All valid
✓ Naming Conventions: Compliant
✓ Bulkification: <bulkSupport>true</bulkSupport> present
✓ Bulkification: No DML in loops
⚠ Warnings: None
✗ Errors: None
Best Practices Score: 100/100 (Excellent ✨)
Recommendations:
1. ✓ Bulkified design - handles collections properly
2. ✓ Fault path configured for error handling
3. ✓ No governor limit issues expected
✓ VALIDATION PASSED - Flow ready for deployment
Phase 4: Deployment
Important: Even though user said "production", skill deploys to sandbox FIRST for testing.
⚠️ IMPORTANT: You specified 'production' but testing in sandbox is
strongly recommended for record-triggered flows.
Deploying to sandbox-test first...
Step 1: Validation (Check-Only)
✓ Metadata structure valid
✓ Opportunity object accessible
✓ Contact object accessible
✓ Status__c field exists on Contact
✓ No deployment conflicts
Step 2: Actual Deployment
✓ Deployed to sandbox-test
✓ Flow status: Draft
✓ Ready for bulk testing
Phase 5: Testing Checklist (CRITICAL for Record-Triggered)
✓ Testing Checklist: Opportunity_Closed_Won_Update_Contacts
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SINGLE RECORD TESTING:
□ Create test Opportunity with Stage = 'Prospecting'
□ Add 2-3 related Contacts
□ Update Opportunity Stage to 'Closed Won'
□ Check Debug Logs - verify flow executed
□ Verify Contacts updated to Status__c = 'Customer'
□ Check no errors in Debug Logs
BULK TESTING (CRITICAL):
□ Prepare 200+ test Opportunities with related Contacts
□ Use Data Loader to bulk update Stage to 'Closed Won'
□ Monitor Debug Logs during bulk update
□ Verify NO governor limit errors
□ Confirm all Contacts updated correctly
□ Check execution time stays within limits
ERROR TESTING:
□ Test with Opportunity that has no related Contacts
□ Test with invalid Contact field values
□ Verify fault path triggers on errors
□ Check error messages are helpful
Debug Logs Query:
sf data query --query "SELECT Id, Status, NumElements FROM FlowInterview
WHERE FlowDefinitionName='Opportunity_Closed_Won_Update_Contacts'
AND CreatedDate=TODAY ORDER BY CreatedDate DESC LIMIT 50"
--target-org sandbox-test
Generated Flow Structure (Key Parts)
Start Element with Bulkification
<start>
<locationX>50</locationX>
<locationY>50</locationY>
<object>Opportunity</object>
<recordTriggerType>CreateAndUpdate</recordTriggerType>
<triggerType>RecordAfterSave</triggerType>
<bulkSupport>true</bulkSupport> <!-- CRITICAL for bulk processing -->
<connector>
<targetReference>Decision_Check_Stage</targetReference>
</connector>
</start>
Decision: Check if Closed Won
<decisions>
<name>Decision_Check_Stage</name>
<label>Check if Closed Won</label>
<rules>
<name>Is_Closed_Won</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>$Record.StageName</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Closed Won</stringValue>
</rightValue>
</conditions>
<connector>
<targetReference>Get_Related_Contacts</targetReference>
</connector>
<label>Is Closed Won</label>
</rules>
</decisions>
Get Records: Related Contacts (Collection)
<recordLookups>
<name>Get_Related_Contacts</name>
<label>Get Related Contacts</label>
<assignNullValuesIfNoRecordsFound>false</assignNullValuesIfNoRecordsFound>
<connector>
<targetReference>Update_Contact_Status</targetReference>
</connector>
<filterLogic>and</filterLogic>
<filters>
<field>AccountId</field>
<operator>EqualTo</operator>
<value>
<elementReference>$Record.AccountId</elementReference>
</value>
</filters>
<object>Contact</object>
<outputReference>colContacts</outputReference> <!-- Collection variable -->
<queriedFields>Id</queriedFields>
<queriedFields>Status__c</queriedFields>
</recordLookups>
Update Records: Bulk Update (NOT in a loop!)
<recordUpdates>
<name>Update_Contact_Status</name>
<label>Update Contact Status</label>
<faultConnector>
<targetReference>Handle_Error</targetReference> <!-- Fault path -->
</faultConnector>
<inputAssignments>
<field>Status__c</field>
<value>
<stringValue>Customer</stringValue>
</value>
</inputAssignments>
<inputReference>colContacts</inputReference> <!-- Updates entire collection -->
</recordUpdates>
Testing Results
Single Record Test
✓ Flow triggered correctly ✓ Stage change detected ✓ Related contacts retrieved (3 contacts) ✓ All 3 contacts updated to Status__c = 'Customer' ✓ Execution time: 142ms ✓ No errors
Bulk Test (200 Opportunities, ~800 Contacts)
✓ Data Loader bulk update completed ✓ Flow executed for all 200 opportunities ✓ All ~800 contacts updated correctly ✓ NO governor limit errors ✓ Average execution time: 287ms per opportunity ✓ Total DML statements: Within limits (150 max) ✓ SOQL queries: Within limits (100 max)
Why it worked:
<bulkSupport>true</bulkSupport>enabled collection processing- DML operation on collection (not individual records in a loop)
- Single SOQL query per opportunity
- Fault paths handled errors gracefully
Common Mistakes (Avoided by This Flow)
❌ WRONG: DML in Loop
<!-- THIS WOULD FAIL WITH BULK DATA -->
<loops>
<name>Loop_Contacts</name>
<collectionReference>colContacts</collectionReference>
<nextValueConnector>
<targetReference>Update_Single_Contact</targetReference> <!-- DML HERE -->
</nextValueConnector>
</loops>
<recordUpdates>
<name>Update_Single_Contact</name>
<!-- This executes INSIDE the loop - CRITICAL ERROR -->
<!-- Hits governor limit with 200+ records -->
</recordUpdates>
Why it fails:
- DML inside loop = one DML per record
- Governor limit: 150 DML statements per transaction
- 200 contacts = 200 DML statements = FAILURE
✓ CORRECT: Bulk DML
<!-- Our flow does this correctly -->
<recordLookups>
<name>Get_Related_Contacts</name>
<outputReference>colContacts</outputReference> <!-- Get collection -->
</recordLookups>
<recordUpdates>
<name>Update_Contact_Status</name>
<inputReference>colContacts</inputReference> <!-- Update entire collection -->
<!-- Single DML operation, regardless of collection size -->
</recordUpdates>
Why it works:
- One DML operation for entire collection
- Handles 200, 2000, or 20,000 records equally well
- Stays within governor limits
Production Deployment
After successful bulk testing in sandbox:
Deploy to production:
"Deploy Opportunity_Closed_Won_Update_Contacts to production"Activate carefully:
- Skill prompts: "Keep as Draft or Activate Now?"
- Select: "Keep as Draft"
- Manually activate after final verification
Monitor in production:
- Check Debug Logs daily for first week
- Review flow interviews for errors
- Monitor performance metrics
Set up monitoring:
sf data query --query "SELECT Id, Status, NumElements FROM FlowInterview WHERE FlowDefinitionName='Opportunity_Closed_Won_Update_Contacts' AND Status='Error' AND CreatedDate=LAST_N_DAYS:1" --target-org production
Performance Metrics
Single Execution:
- SOQL Queries: 1 (Get Contacts)
- DML Statements: 1 (Update Contacts)
- Execution Time: ~150ms
Bulk Execution (200 Opportunities):
- SOQL Queries: 200 (1 per opportunity)
- DML Statements: 200 (1 per opportunity)
- Total Time: ~58 seconds
- NO governor limit errors
Key Takeaways
✓ ALWAYS set <bulkSupport>true</bulkSupport> for record-triggered flows ✓ NEVER put DML inside loops - causes bulk failures ✓ Use collections - get all records, update all at once ✓ Add fault paths - handle errors gracefully ✓ Test with bulk data - 200+ records minimum ✓ Monitor in production - check Debug Logs regularly
This is production-grade, bulkified Flow design!
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Screen Flow Example: Customer Feedback Form
Version: 2.0.0 Demonstrates: UX patterns, progress indicators, navigation controls, error recovery
This example demonstrates creating a Screen Flow that collects customer feedback and creates a custom object record, following v2.0.0 UX best practices.
Scenario
Create an interactive form where users can:
- Select a product from a picklist
- Rate their experience (1-5 stars)
- Provide comments
- Submit feedback to a custom Feedback__c object
User Request
User: "Create a screen flow for customer feedback collection.
It should have a welcome screen, collect product selection,
rating (1-5), and comments, then save to the Feedback__c object."
UX Design Patterns (v2.0.0)
Flow Structure with Navigation
┌────────────────────────────────────────────────────────────────┐
│ SCREEN 1: Welcome │
│ ───────────────────────── │
│ "Customer Feedback" (Step 1 of 3) │
│ │
│ Welcome message and instructions │
│ │
│ allowBack: false │ allowFinish: true │ Button: [Next] │
└────────────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────┐
│ SCREEN 2: Feedback Form │
│ ───────────────────────── │
│ "Enter Your Feedback" (Step 2 of 3) │
│ │
│ Product: [Dropdown] │
│ Rating: ★ ★ ★ ★ ★ (1-5) │
│ Comments: [Text Area] │
│ │
│ allowBack: true │ allowFinish: true │ [Previous] [Next] │
└────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────┐
│ Create Record │──fault──▶ Error Screen
└────────┬────────┘
│ success
▼
┌────────────────────────────────────────────────────────────────┐
│ SCREEN 3: Thank You │
│ ───────────────────── │
│ "Success!" (Step 3 of 3) │
│ │
│ ✓ Thank you for your feedback! │
│ │
│ allowBack: false │ allowFinish: true │ Button: [Finish] │
│ (prevents duplicate submissions) │
└────────────────────────────────────────────────────────────────┘
Navigation Control Rules Applied
| Screen | allowBack | allowFinish | Reason |
|---|---|---|---|
| Welcome | false |
true |
First screen - no previous |
| Feedback Form | true |
true |
Allow user to go back |
| Thank You | false |
true |
Record already created - prevent duplicate |
| Error | true |
true |
Let user try again |
Generated Flow Structure (v2.0.0)
Variables (with v2.0.0 Naming Prefixes)
<!-- Input/Form Variables -->
<variables>
<name>var_ProductName</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>var_Rating</name>
<dataType>Number</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
<scale>0</scale>
</variables>
<variables>
<name>var_Comments</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Error Handling Variable -->
<variables>
<name>var_ErrorMessage</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>false</isOutput>
</variables>
<!-- Output Variable for Integration -->
<variables>
<name>out_FeedbackId</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>true</isOutput>
</variables>
Screen 1: Welcome (with Progress Indicator)
<screens>
<name>Screen_Welcome</name>
<label>Welcome</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>false</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<connector>
<targetReference>Screen_Feedback_Form</targetReference>
</connector>
<fields>
<!-- Progress Indicator Header -->
<name>Welcome_Header</name>
<fieldType>DisplayText</fieldType>
<fieldText><p><b style="font-size: 20px;">Customer Feedback</b></p><p><span style="color: rgb(107, 107, 107);">Step 1 of 3</span></p></fieldText>
</fields>
<fields>
<!-- Instructions -->
<name>Welcome_Instructions</name>
<fieldType>DisplayText</fieldType>
<fieldText><p>Thank you for taking the time to share your feedback!</p><p><br></p><p>Your input helps us improve our products and services. This form takes approximately <b>2 minutes</b> to complete.</p><p><br></p><p>Click <b>Next</b> to begin.</p></fieldText>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
Screen 2: Feedback Form (with Input Validation)
<screens>
<name>Screen_Feedback_Form</name>
<label>Feedback Form</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>true</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<connector>
<targetReference>Create_Feedback_Record</targetReference>
</connector>
<fields>
<!-- Progress Header -->
<name>Form_Header</name>
<fieldType>DisplayText</fieldType>
<fieldText><p><b style="font-size: 20px;">Enter Your Feedback</b></p><p><span style="color: rgb(107, 107, 107);">Step 2 of 3</span></p></fieldText>
</fields>
<fields>
<!-- Instructions with Required Field Indicator -->
<name>Form_Instructions</name>
<fieldType>DisplayText</fieldType>
<fieldText><p>Please complete all required fields (<span style="color: rgb(194, 57, 52);">*</span>) below.</p></fieldText>
</fields>
<fields>
<!-- Product Selection (Required) -->
<name>Input_Product</name>
<choiceReferences>choice_Product_A</choiceReferences>
<choiceReferences>choice_Product_B</choiceReferences>
<choiceReferences>choice_Product_C</choiceReferences>
<dataType>String</dataType>
<fieldText>Which product are you providing feedback for?</fieldText>
<fieldType>DropdownBox</fieldType>
<isRequired>true</isRequired>
<inputsOnNextNavToAssocScrn>UseStoredValues</inputsOnNextNavToAssocScrn>
</fields>
<fields>
<!-- Rating (1-5, Required) -->
<name>Input_Rating</name>
<dataType>Number</dataType>
<fieldText>How would you rate your experience? (1-5)</fieldText>
<fieldType>InputField</fieldType>
<helpText>1 = Very Poor, 5 = Excellent</helpText>
<isRequired>true</isRequired>
<scale>0</scale>
<inputsOnNextNavToAssocScrn>UseStoredValues</inputsOnNextNavToAssocScrn>
</fields>
<fields>
<!-- Comments (Optional) -->
<name>Input_Comments</name>
<fieldText>Additional Comments (Optional)</fieldText>
<fieldType>LargeTextArea</fieldType>
<helpText>Share any additional thoughts, suggestions, or concerns.</helpText>
<isRequired>false</isRequired>
<inputsOnNextNavToAssocScrn>UseStoredValues</inputsOnNextNavToAssocScrn>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
Record Create (with Fault Connector)
<recordCreates>
<name>Create_Feedback_Record</name>
<label>Create Feedback Record</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Screen_Thank_You</targetReference>
</connector>
<faultConnector>
<targetReference>Capture_Error</targetReference>
</faultConnector>
<inputAssignments>
<field>Product__c</field>
<value>
<elementReference>Input_Product</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<field>Rating__c</field>
<value>
<elementReference>Input_Rating</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<field>Comments__c</field>
<value>
<elementReference>Input_Comments</elementReference>
</value>
</inputAssignments>
<object>Feedback__c</object>
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordCreates>
Screen 3: Thank You (Back Button DISABLED)
<!--
CRITICAL: allowBack="false" on success screen!
The record has already been created. If we allow back navigation,
the user could submit again and create duplicate records.
-->
<screens>
<name>Screen_Thank_You</name>
<label>Thank You</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>false</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<!-- No connector = "Finish" button displayed -->
<fields>
<name>ThankYou_Header</name>
<fieldType>DisplayText</fieldType>
<fieldText><p><b style="font-size: 20px;">Success!</b></p><p><span style="color: rgb(107, 107, 107);">Step 3 of 3</span></p></fieldText>
</fields>
<fields>
<name>ThankYou_Message</name>
<fieldType>DisplayText</fieldType>
<fieldText><p><span style="color: rgb(46, 132, 74); font-size: 24px;">✓</span></p><p><br></p><p><b>Thank you for your feedback!</b></p><p><br></p><p>Your input has been recorded and will help us improve our products and services.</p><p><br></p><p>Click <b>Finish</b> to close this form.</p></fieldText>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
Error Recovery Screen (Back Button ENABLED)
<!-- Capture Error Message -->
<assignments>
<name>Capture_Error</name>
<label>Capture Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<assignmentItems>
<assignToReference>var_ErrorMessage</assignToReference>
<operator>Assign</operator>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</assignmentItems>
<connector>
<targetReference>Screen_Error</targetReference>
</connector>
</assignments>
<!--
ERROR SCREEN: allowBack="true"
Let users go back to fix their input and try again.
The record wasn't created, so no duplicate risk.
-->
<screens>
<name>Screen_Error</name>
<label>Error</label>
<locationX>0</locationX>
<locationY>0</locationY>
<allowBack>true</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<fields>
<name>Error_Header</name>
<fieldType>DisplayText</fieldType>
<fieldText><p><span style="color: rgb(194, 57, 52);"><b style="font-size: 20px;">Something Went Wrong</b></span></p></fieldText>
</fields>
<fields>
<name>Error_Message</name>
<fieldType>DisplayText</fieldType>
<fieldText><p>We were unable to save your feedback. The error was:</p><p><br></p><p><i style="color: rgb(194, 57, 52);">{!var_ErrorMessage}</i></p><p><br></p><p>Please click <b>Previous</b> to review your entries and try again, or click <b>Finish</b> to exit without saving.</p></fieldText>
</fields>
<showFooter>true</showFooter>
<showHeader>true</showHeader>
</screens>
UX Best Practices Demonstrated
1. Progress Indicators
Every screen shows "Step X of 3" to orient users.
2. Clear Instructions
- Welcome screen explains time commitment (2 minutes)
- Form screen explains required fields (*)
- Help text on complex fields
3. Input Preservation
inputsOnNextNavToAssocScrn="UseStoredValues" preserves user input when navigating back.
4. Strategic Back Button Control
| Screen | allowBack | Reason |
|---|---|---|
| Welcome | false | No previous screen |
| Form | true | Let users go back to re-read instructions |
| Thank You | false | Prevent duplicate submission |
| Error | true | Let users try again |
5. User-Friendly Error Messages
- Technical
$Flow.FaultMessagedisplayed in italic - Clear instruction on recovery options
- Both "Previous" and "Finish" available
6. Consistent Visual Hierarchy
- Large, bold headers (20px)
- Subdued progress text (gray)
- Success confirmation with checkmark
- Error text in red
Testing Checklist (v2.0.0)
Path Coverage
- Happy path: Welcome → Form → Create → Thank You
- Error path: Welcome → Form → Error → (Previous) → Form → Success
- Exit from error: Welcome → Form → Error → Finish
Navigation Testing
- Welcome: No "Previous" button visible
- Form: Both "Previous" and "Next" visible
- Thank You: No "Previous" button (prevents duplicate)
- Error: Both "Previous" and "Finish" visible
Input Validation
- Empty product → validation message
- Rating 0 or 6 → validation message (if min/max configured)
- All required fields empty → validation messages
- Long comments (32,000+ chars) → handled gracefully
User Context
- Works as System Administrator
- Works as Standard User
- Works as Community User (if exposed externally)
Edge Cases
- Special characters in comments:
<>&"' - Unicode/Emoji in comments
- Browser back button behavior
- Session timeout handling
Skill Workflow
Phase 1: Requirements Gathering
The skill asks:
Q1: What type of flow? → Screen Flow
Q2: What is the purpose? → "Collect customer feedback and save to Feedback__c object"
Q3: Target org? → "sandbox"
Phase 2: Flow Design
The skill designs:
- Screen 1: Welcome message with progress indicator
- Screen 2: Feedback form with validation
- Create Record: Save to Feedback__c (with fault path)
- Screen 3: Thank you confirmation (back disabled)
- Error Screen: Recovery option (back enabled)
Phase 3: Validation
Flow Validation Report: Customer_Feedback_Screen_Flow (API 66.0)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Score: 108/110 ⭐⭐⭐⭐⭐ Excellent
├─ Design & Naming: 20/20 (100%) ✓
├─ Logic & Structure: 20/20 (100%) ✓
├─ Architecture: 13/15 (87%)
├─ Performance & Bulk Safety: 20/20 (100%) ✓
├─ Error Handling: 20/20 (100%) ✓
└─ Security: 15/15 (100%) ✓
✓ Variable naming follows v2.0.0 prefixes (var_, out_)
✓ All DML has fault connectors
✓ Progress indicators on all screens
✓ Back button disabled on success screen
✓ VALIDATION PASSED - Flow ready for deployment
Phase 4: Deployment
Step 1: Check-Only Validation
Deploying flow with --dry-run flag...
✓ Validation successful
✓ No org-specific errors
✓ Ready for actual deployment
Step 2: Actual Deployment
Deploying to sandbox...
✓ Deployment successful
Job ID: 0Af5g00000XXXXX
Flow deployed as Draft
Phase 5: Testing
Follow the testing checklist above, then activate when ready.
Related Resources
- Screen Flow Template - Base template with UX guidance
- Flow Best Practices - Comprehensive UX patterns
- Testing Guide - Testing strategies
- Testing Checklist - Quick reference
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Reusable Subflow Library
Overview
The Subflow Library provides pre-built, production-ready subflows that accelerate flow development and enforce best practices. Instead of recreating common patterns, use these standardized components to build flows faster while maintaining consistency.
Benefits:
- ⚡ Faster Development: Pre-built patterns save 30-50% development time
- 🔒 Built-in Error Handling: Fault paths and logging included
- ✅ Best Practices: Bulkified, tested, and validated
- 🔄 Reusable: One subflow, many parent flows
- 📊 Maintainable: Update once, improve everywhere
Available Subflows
1. Sub_LogError
Purpose: Structured error logging for fault paths
File: assets/subflows/subflow-error-logger.xml
When to Use:
- In fault paths of DML operations
- When you need to capture and track flow failures
- For production observability and debugging
Input Variables:
varFlowName(String): Name of the calling flowvarRecordId(String): ID of the record being processedvarErrorMessage(String): Error message (typically$Flow.FaultMessage)
Output Variables: None
Example:
<subflows>
<name>Log_Update_Error</name>
<flowName>Sub_LogError</flowName>
<inputAssignments>
<name>varFlowName</name>
<value>
<stringValue>RTF_Account_UpdateIndustry</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varRecordId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varErrorMessage</name>
<value>
<elementReference>$Flow.FaultMessage</elementReference>
</value>
</inputAssignments>
</subflows>
Prerequisites: Create Flow_Error_Log__c custom object with fields:
Flow_Name__c(Text, 255)Record_Id__c(Text, 18)Error_Message__c(Long Text Area, 32,768)
Related: Error Logging Example
2. Sub_SendEmailAlert
Purpose: Standard email notifications
File: assets/subflows/subflow-email-alert.xml
When to Use:
- Send notifications when certain conditions are met
- Alert users about flow completion or errors
- Standardize email formatting across flows
Input Variables:
varEmailAddresses(String): Comma-separated email addressesvarEmailSubject(String): Email subject linevarEmailBody(String): Email body content
Output Variables: None
Example:
<subflows>
<name>Notify_Manager</name>
<flowName>Sub_SendEmailAlert</flowName>
<inputAssignments>
<name>varEmailAddresses</name>
<value>
<elementReference>$Record.Manager.Email</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varEmailSubject</name>
<value>
<stringValue>High-Value Opportunity Created</stringValue>
</value>
</inputAssignments>
<inputAssignments>
<name>varEmailBody</name>
<value>
<stringValue>A new opportunity worth {!$Record.Amount} has been created.</stringValue>
</value>
</inputAssignments>
</subflows>
Best Practices:
- Use formula fields or text templates to build dynamic email bodies
- Consider using email templates instead for complex HTML emails
- Validate email addresses before passing to subflow
3. Sub_ValidateRecord
Purpose: Common validation patterns
File: assets/subflows/subflow-record-validator.xml
When to Use:
- Validate required fields before DML operations
- Check business rules before proceeding
- Return validation status to parent flow
Input Variables:
varFieldValue(String): Field value to validate
Output Variables:
varIsValid(Boolean):trueif validation passed,falseotherwisevarValidationMessage(String): Validation result message
Example:
<subflows>
<name>Validate_Industry</name>
<flowName>Sub_ValidateRecord</flowName>
<inputAssignments>
<name>varFieldValue</name>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Decision based on validation result -->
<decisions>
<name>Check_Validation</name>
<rules>
<name>Valid</name>
<conditions>
<leftValueReference>Validate_Industry.varIsValid</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<booleanValue>true</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Proceed_With_Update</targetReference>
</connector>
</rules>
<defaultConnector>
<targetReference>Show_Error_Screen</targetReference>
</defaultConnector>
</decisions>
Extension: Customize the validation logic in the subflow for your specific needs:
- Add more complex rules (regex, format checks)
- Validate multiple fields
- Check against external systems
4. Sub_UpdateRelatedRecords
Purpose: Bulk update pattern with error handling
File: assets/subflows/subflow-bulk-updater.xml
When to Use:
- Update collections of related records
- Maintain bulkification best practices
- Centralize common update logic
Input Variables:
colRecordsToUpdate(SObject Collection): Collection of records to updatevarNewValue(String): New value to assign (customize for your field type)
Output Variables: None
Example:
<!-- First, collect records in a loop -->
<loops>
<name>Loop_Through_Contacts</name>
<collectionReference>Get_Related_Contacts</collectionReference>
<iterationOrder>Asc</iterationOrder>
<nextValueConnector>
<targetReference>Add_To_Collection</targetReference>
</nextValueConnector>
<noMoreValuesConnector>
<targetReference>Call_Bulk_Updater</targetReference>
</noMoreValuesConnector>
</loops>
<assignments>
<name>Add_To_Collection</name>
<assignmentItems>
<assignToReference>colContactsToUpdate</assignToReference>
<operator>Add</operator>
<value>
<elementReference>Loop_Through_Contacts</elementReference>
</value>
</assignmentItems>
<connector>
<targetReference>Loop_Through_Contacts</targetReference>
</connector>
</assignments>
<!-- Then, call subflow OUTSIDE the loop -->
<subflows>
<name>Call_Bulk_Updater</name>
<flowName>Sub_UpdateRelatedRecords</flowName>
<inputAssignments>
<name>colRecordsToUpdate</name>
<value>
<elementReference>colContactsToUpdate</elementReference>
</value>
</inputAssignments>
<inputAssignments>
<name>varNewValue</name>
<value>
<elementReference>$Record.Industry</elementReference>
</value>
</inputAssignments>
</subflows>
Key Pattern: ✅ Correct: Loop → Add to Collection → (Outside Loop) → Call Subflow with Collection ❌ Incorrect: Loop → Call Subflow → (DML in loop!)
5. Sub_QueryRecordsWithRetry
Purpose: Query with built-in error handling
File: assets/subflows/subflow-query-with-retry.xml
When to Use:
- Query related records with fault handling
- Standardize query patterns
- Log query failures for troubleshooting
Input Variables:
varAccountId(String): Filter criteria (customize for your query)
Output Variables:
- Automatically stores query results (use
storeOutputAutomatically="true")
Example:
<subflows>
<name>Get_Related_Contacts</name>
<flowName>Sub_QueryRecordsWithRetry</flowName>
<inputAssignments>
<name>varAccountId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<storeOutputAutomatically>true</storeOutputAutomatically>
</subflows>
<!-- Access query results -->
<decisions>
<name>Check_Results</name>
<rules>
<name>Contacts_Found</name>
<conditions>
<leftValueReference>Get_Related_Contacts</leftValueReference>
<operator>IsNull</operator>
<rightValue>
<booleanValue>false</booleanValue>
</rightValue>
</conditions>
<connector>
<targetReference>Process_Contacts</targetReference>
</connector>
</rules>
<defaultConnector>
<targetReference>No_Contacts_Path</targetReference>
</defaultConnector>
</decisions>
Customization: Modify the query filters in the template for your specific object and criteria.
Deployment Guide
Step 1: Deploy Subflows to Your Org
# Deploy all subflows at once
sf project deploy start \
--source-dir assets/subflows/ \
--target-org myorg
# Or deploy individually
sf project deploy start \
--source-dir assets/subflows/subflow-error-logger.xml \
--target-org myorg
Step 2: Activate Subflows
- Navigate to Setup → Flows
- Find each subflow (Sub_LogError, Sub_SendEmailAlert, etc.)
- Click Activate
⚠️ Important: Deploy Sub_LogError first if other subflows use it for error handling.
Step 3: Create Required Custom Objects
For Sub_LogError, create the Flow_Error_Log__c object:
# Using Salesforce CLI
sf data create record \
--sobject CustomObject \
--values "FullName=Flow_Error_Log__c Label='Flow Error Log' PluralLabel='Flow Error Logs'"
Or manually in Setup → Object Manager → Create → Custom Object.
Usage Patterns
Pattern 1: Orchestrated Error Handling
Use Sub_LogError consistently across all flows:
Parent Flow
├── DML Operation 1 → [Fault] → Sub_LogError
├── DML Operation 2 → [Fault] → Sub_LogError
└── Subflow Call → [Fault] → Sub_LogError
Pattern 2: Modular Notifications
Centralize all email logic in Sub_SendEmailAlert:
Record-Triggered Flow
├── Decision: High Value?
│ ├── Yes → Sub_SendEmailAlert(Manager)
│ └── No → End
└── Decision: Overdue?
├── Yes → Sub_SendEmailAlert(Owner)
└── No → End
Pattern 3: Validation Pipeline
Chain validation subflows before DML:
Screen Flow
├── Sub_ValidateRecord(Required Fields)
│ └── Invalid? → Show Error
├── Sub_ValidateRecord(Business Rules)
│ └── Invalid? → Show Error
└── All Valid → Create Record
Best Practices
✅ DO:
- Deploy Once, Reference Everywhere: Activate subflows in your org, then reference them in multiple parent flows
- Use Naming Conventions: Start subflow names with
Sub_for easy identification - Add Fault Paths: Connect all DML operations in subflows to error handlers
- Document Inputs/Outputs: Use clear variable names (varFieldName, colRecordCollection)
- Version Control: Track subflow changes and test before updating active versions
❌ DON'T:
- Don't Copy-Paste Subflows: Reference the deployed subflow instead of duplicating logic
- Don't Skip Error Handling: All subflows should handle their own errors gracefully
- Don't Hardcode Values: Use input variables for flexibility
- Don't Create DML in Loops: Use Sub_UpdateRelatedRecords pattern for bulk operations
- Don't Forget Testing: Test subflows independently before using in parent flows
Testing Your Subflows
Unit Testing Individual Subflows
- Create a test flow that calls the subflow
- Pass various input combinations (valid, invalid, null)
- Verify output variables and behavior
- Check error logs if using Sub_LogError
# Example: Test Sub_LogError
sf data query \
--query "SELECT Flow_Name__c, Error_Message__c FROM Flow_Error_Log__c ORDER BY CreatedDate DESC LIMIT 5" \
--target-org myorg
Integration Testing in Parent Flows
- Use subflows in record-triggered flows
- Test with bulk data (200+ records)
- Verify subflow doesn't cause governor limit errors
- Check execution time in debug logs
Customization Guide
Extending Subflows
All subflows are templates—customize for your needs:
- Clone the subflow: Create a copy (e.g.,
Sub_LogError_WithEmail) - Add custom logic: Extend functionality while keeping core pattern
- Maintain naming convention: Keep
Sub_prefix for discoverability
Example: Enhanced Error Logger
Extend Sub_LogError to send Platform Events:
<!-- Add to subflow after Create_Error_Log -->
<recordCreates>
<name>Publish_Error_Event</name>
<object>Flow_Error__e</object>
<inputAssignments>
<field>Flow_Name__c</field>
<value>
<elementReference>varFlowName</elementReference>
</value>
</inputAssignments>
<!-- Real-time error monitoring -->
</recordCreates>
Performance Considerations
Governor Limits
- Subflow Depth: Maximum 50 levels of nested subflows (avoid deep nesting)
- DML Statements: Each subflow DML counts toward 150 limit
- SOQL Queries: Each subflow query counts toward 100 limit
Optimization Tips
- Batch Operations: Use Sub_UpdateRelatedRecords for bulk updates
- Minimize Subflow Calls: Call once with collections vs. multiple times with single records
- Cache Results: Store subflow outputs in variables to avoid repeated calls
Troubleshooting
"Subflow not found" Error
- ✅ Verify subflow is activated in target org
- ✅ Check API name matches exactly (
Sub_LogError, notSub_Log_Error) - ✅ Deploy subflow before deploying parent flow
"Input variable not found" Error
- ✅ Verify variable names match subflow definition
- ✅ Check variable data types (String vs. SObject Collection)
- ✅ Ensure required inputs are provided
Performance Issues
- ✅ Check debug logs for subflow execution time
- ✅ Avoid calling subflows inside loops
- ✅ Use bulk operations with collections
Version History
| Version | Date | Changes |
|---|---|---|
| 1.0 | 2024-11-30 | Initial library: 5 subflows (LogError, EmailAlert, Validator, BulkUpdater, QueryWithRetry) |
Related Documentation
- Error Logging Example - Detailed Sub_LogError usage
- Orchestration Guide - Parent-child flow patterns
- Flow Best Practices - Flow guidelines and security
Support
For issues or questions:
- Check subflow XML for correct variable names and types
- Test subflow independently before using in parent flow
- Review error logs in Flow_Error_Log__c (if using Sub_LogError)
- Check debug logs for detailed execution information
Happy flow building! 🚀
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flow Testing Checklist
Version: 2.0.0 Purpose: Quick-reference checklist for flow testing Usage: Copy and use for each flow deployment
Pre-Testing Setup
- Flow XML validates without errors
- All decision paths documented
- Test data prepared in sandbox
- Debug logs enabled for test user
Path Coverage
- All decision branches tested (including default)
- All loop scenarios tested:
- 0 items (empty collection)
- 1 item
- Many items (10+)
- All fault paths tested
- Positive cases pass (valid inputs)
- Negative cases handled gracefully (invalid inputs)
Bulk Testing
- Single record works correctly
- 10-20 records work (basic bulkification)
- 200+ records work (no governor limit errors)
- No DML-in-loop errors in debug logs
Edge Cases
- Null values handled (no crashes)
- Empty collections handled (loops skip gracefully)
- Max field lengths work (no truncation)
- Special characters work (
<>&"') - Date edge cases work (leap years, boundaries)
User Context
- Works as System Administrator
- Works as Standard User
- FLS restrictions enforced (User mode flows)
- Sharing rules respected
- Custom permissions work (
$Permission)
Error Handling
- All DML elements have fault paths
- Error messages are user-friendly
- Rollback logic works (if multi-step DML)
- Error logging captures context
Screen Flow Specific
- All navigation works (Next/Previous/Finish)
- Input validation works on each screen
- Conditional visibility works
- Progress indicator updates (if applicable)
- Back button behavior correct
Record-Triggered Specific
- Entry conditions filter correctly
- Before-save vs After-save timing correct
-
$Recordvalues accessible - Re-entry prevention works (if applicable)
Scheduled Flow Specific
- Schedule configuration verified
- Manual run test passes
- Empty result set handled
- Batch processing works
Deployment
-
checkOnly=truedeployment succeeds - package.xml API version matches flow
- Test in sandbox complete
- Activation plan documented
Post-Deployment
- Flow status verified (Active/Draft)
- Correct version is active
- No errors in Flow Errors log
- First execution monitored
Sign-Off
| Item | Completed | Date | Tester |
|---|---|---|---|
| Development Testing | |||
| UAT Testing | |||
| Bulk Testing | |||
| Security Review | |||
| Production Deployment |
Notes
Add any flow-specific notes or exceptions here
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Salesforce Flow Testing Guide
Version: 2.0.0 Last Updated: December 2025 Purpose: Comprehensive testing strategies for all Salesforce Flow types
This guide provides structured testing approaches to ensure your flows work correctly under all conditions.
Table of Contents
- Test Path Coverage
- Graduated Bulk Testing
- Edge Case Checklist
- User Context Testing
- Flow Type-Specific Testing
- Deployment Testing Sequence
- Regression Testing
- Governor Limits Testing
- Post-Deployment Verification
1. Test Path Coverage
Before testing, map every possible route through your flow.
Identify All Paths
Document these for every flow:
- Decision element outcomes (all branches, including default)
- Loop iterations (0 items, 1 item, many items)
- Fault paths (every DML element's error path)
- Conditional screens (all visibility combinations)
Test Matrix Template
Create a test matrix for each flow:
| Test Case ID | Path Description | Input Data | Expected Output | Actual Result | Pass/Fail |
|---|---|---|---|---|---|
| TC-001 | Happy path - all valid | Valid Account data | Record created | ||
| TC-002 | Null input - missing required | AccountId = null | Error message shown | ||
| TC-003 | Empty collection | 0 records from query | Loop skips, no DML | ||
| TC-004 | Fault path - DML fails | Invalid record data | Error logged, user notified | ||
| TC-005 | Decision branch A | Type = 'Customer' | Customer logic runs | ||
| TC-006 | Decision branch B | Type = 'Partner' | Partner logic runs |
Positive vs Negative Testing
Positive Testing: Valid inputs → Expected successful outcomes
- Correct data formats
- Required fields populated
- Valid record IDs
Negative Testing: Invalid inputs → Graceful failure/error handling
- Missing required values
- Invalid formats
- Non-existent record IDs
- Null values where not expected
2. Graduated Bulk Testing
Test in this progression to isolate issues:
| Stage | Record Count | Purpose | What to Check |
|---|---|---|---|
| 1 | Single (1) | Logic correctness | Flow completes, correct output |
| 2 | Small batch (10-20) | Basic bulkification | No obvious errors |
| 3 | Medium batch (50-100) | Performance baseline | Execution time acceptable |
| 4 | Large batch (200+) | Governor limit validation | No limit exceeded errors |
| 5 | Stress test (10,000+) | Edge case (optional) | System stability |
Why 200+ Records?
- Record-triggered flows fire in batches of 200
- Testing at this level ensures your flow survives real-world triggers
- Data Loader operations commonly process 200 records per batch
How to Bulk Test
Via Data Loader:
- Create CSV with test data (200+ rows)
- Load via Data Loader or Workbench
- Monitor Debug Logs during execution
Via Apex:
@isTest
static void testBulkTrigger() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test ' + i));
}
Test.startTest();
insert accounts; // Triggers record-triggered flow
Test.stopTest();
// Assert expected outcomes
System.assertEquals(200, [SELECT COUNT() FROM Account WHERE Name LIKE 'Test%']);
}
Via Flow Simulator:
python3 validators/flow_simulator.py \
force-app/main/default/flows/[FlowName].flow-meta.xml \
--test-records 200
3. Edge Case Checklist
Always test these scenarios:
| Edge Case | Test Scenario | What to Verify |
|---|---|---|
| Null values | Required field is null | Error handling activates, no crash |
| Empty collections | Get Records returns 0 | Loop skips gracefully, no null errors |
| Max field lengths | 255-char text, max picklist | No truncation errors |
| Special characters | <>&"' in text fields |
No XML/formula breaks |
| Unicode/Emoji | International characters, emojis | Proper encoding maintained |
| Date boundaries | Year 2000, 2038, leap years | Date calculations work correctly |
| Negative numbers | -1, MIN_INT values | Math operations handle correctly |
| Large numbers | MAX_INT, currency limits | No overflow errors |
| Blank strings | Empty string vs null | Handled differently if expected |
| Whitespace | Leading/trailing spaces | Trimmed or preserved as designed |
Creating Edge Case Test Data
// Edge case test data
Account edgeCaseAccount = new Account(
Name = 'Test <Special> & "Characters"', // Special chars
Description = String.valueOf(Crypto.getRandomLong()), // Max length test
AnnualRevenue = -100 // Negative number
);
4. User Context Testing
Test with multiple user profiles to verify security.
Minimum Test Profiles
| Profile | Purpose | What to Verify |
|---|---|---|
| System Administrator | Full access baseline | All features work |
| Standard User | Limited permissions | FLS/CRUD enforced |
| Custom Profile | Business-specific restrictions | Custom permissions work |
| Community User (if applicable) | External access | Portal restrictions apply |
What to Verify
- Field-Level Security (FLS): Restricted fields not visible
- Record sharing rules: Access limited to owned/shared records
- Custom permissions:
$Permissionglobal variable works - System mode vs User mode: Behaves as designed
Testing with Different Users
CLI Approach:
# Authenticate as different user (sf org login user does not exist)
sf org login web --alias standard-user-org
# Note: To test as different users, authenticate separate orgs or use sf org login jwt with per-user credentials
# Run tests/verify behavior
Apex Test Approach:
@isTest
static void testAsStandardUser() {
User standardUser = [SELECT Id FROM User WHERE Profile.Name = 'Standard User' LIMIT 1];
System.runAs(standardUser) {
// Test flow behavior as this user
// Verify FLS/CRUD restrictions
}
}
User Mode Flow Testing
For flows running in User Mode, verify:
- Users cannot access records they don't have permission to
- Field-level security is enforced
- Sharing rules are respected
System Mode Flow Testing
For flows running in System Mode:
- Document justification for bypassing security
- Verify flow doesn't expose sensitive data inappropriately
- Test that security-sensitive operations are logged
<a id="5-flow-type-specific-testing"></a>
5. Flow Type-Specific Testing
Screen Flows
Launch Methods:
- Setup → Flows → Run
- Direct URL:
https://[org].lightning.force.com/flow/[FlowApiName] - Embedded in Lightning page
Test Checklist:
- All navigation paths (Next/Previous/Finish)
- Input validation on each screen
- Conditional field visibility
- Multiple user profiles
- Error messages display correctly
- Progress indicator updates (if multi-step)
- Back button behavior (data preserved or re-queried)
Record-Triggered Flows
CRITICAL: Always bulk test with 200+ records.
Test Checklist:
- Create single test record - verify trigger fires
- Bulk test via Data Loader (200+ records)
- Entry conditions work correctly
- Before-save vs After-save timing correct
-
$Recordand$Record__Priorvalues correct - Re-entry prevention working (if applicable)
Query Recent Executions:
sf data query --query "SELECT Id, Status, CreatedDate FROM FlowInterview WHERE FlowDeveloperName='[FlowName]' ORDER BY CreatedDate DESC LIMIT 10" --target-org [org]
Autolaunched Flows
Test via Apex:
Map<String, Object> inputs = new Map<String, Object>{
'inputRecordId' => testRecord.Id,
'inputAmount' => 1000
};
Flow.Interview.My_Autolaunched_Flow flow = new Flow.Interview.My_Autolaunched_Flow(inputs);
flow.start();
// Get output variables
String result = (String) flow.getVariableValue('outputResult');
System.assertEquals('Success', result);
Test Checklist:
- Input variable mapping correct
- Output variable values correct
- Edge cases: nulls, empty collections, max values
- Bulkification test (200+ records)
- Governor limits not exceeded
Scheduled Flows
Test Checklist:
- Verify schedule configuration in Setup → Scheduled Jobs
- Manual "Run" test first (before enabling schedule)
- Monitor Debug Logs during execution
- Batch processing works correctly
- Verify record selection criteria
- Test with empty result set (no records match)
- Cleanup/completion logic works
Verify Schedule:
sf data query --query "SELECT Id, CronJobDetail.Name, State, NextFireTime FROM CronTrigger WHERE CronJobDetail.Name LIKE '%[FlowName]%'" --target-org [org]
Platform Event-Triggered Flows
Publish Test Event:
// Publish event
My_Event__e event = new My_Event__e(
Record_Id__c = testRecord.Id,
Action__c = 'CREATE'
);
Database.SaveResult sr = EventBus.publish(event);
System.assert(sr.isSuccess());
Test Checklist:
- Flow triggers on event publication
- Event data accessible via
$Record - High-volume scenarios work (multiple events)
- Order of processing correct
- Error handling works for failed events
6. Deployment Testing Sequence
Follow this 5-step deployment validation:
| Step | Action | Tool/Method | Success Criteria |
|---|---|---|---|
| 1 | Validate XML structure | Flow validator scripts | No errors |
| 2 | Deploy with checkOnly=true | sf project deploy start --dry-run |
Deployment succeeds |
| 3 | Verify package.xml | Manual review | API version matches flow |
| 4 | Test with minimal data | 1-5 records in sandbox | Basic functionality works |
| 5 | Test with bulk data | 200+ records in sandbox | Governor limits OK |
Dry-Run Deployment
# Validate without deploying
sf project deploy start --source-dir force-app --dry-run --target-org sandbox
# Check deployment status
sf project deploy report --target-org sandbox
Package.xml Verification
Ensure API version matches:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>My_Flow</members>
<name>Flow</name>
</types>
<version>66.0</version> <!-- Must match flow's apiVersion -->
</Package>
7. Regression Testing
Document Test Cases
Maintain a test case document for each flow:
| Field | Description |
|---|---|
| Test Case ID | Unique identifier (TC-001) |
| Description | What this test verifies |
| Pre-conditions | Required setup before test |
| Steps | Numbered steps to execute |
| Expected Result | What should happen |
| Last Tested | Date and version |
After Every Change
Re-run ALL test cases, not just changed paths:
- Logic changes can have cascading effects
- Decision criteria changes affect multiple branches
- Variable changes impact downstream elements
Integration Testing
Test interactions with:
- Other flows on the same object (trigger order)
- Process Builders (legacy - if still active)
- Apex triggers (execution order matters)
- Validation rules (may block flow DML)
- Workflow rules (legacy - field updates)
- External integrations (API calls, platform events)
Automated Regression Testing
Consider creating Apex test classes that:
- Invoke flows programmatically
- Assert expected outcomes
- Run as part of CI/CD pipeline
@isTest
static void testFlowRegressionSuite() {
// Setup test data
Account testAccount = new Account(Name = 'Test');
insert testAccount;
// Invoke flow
Map<String, Object> inputs = new Map<String, Object>{
'recordId' => testAccount.Id
};
Flow.Interview.My_Flow flow = new Flow.Interview.My_Flow(inputs);
flow.start();
// Assert expected outcomes
testAccount = [SELECT Status__c FROM Account WHERE Id = :testAccount.Id];
System.assertEquals('Processed', testAccount.Status__c);
}
8. Governor Limits Testing
Limit Thresholds
| Limit | Value | Warning Threshold |
|---|---|---|
| SOQL Queries | 100 | 80 |
| DML Statements | 150 | 120 |
| Records Retrieved | 50,000 | 40,000 |
| DML Rows | 10,000 | 8,000 |
| CPU Time | 10,000 ms | 8,000 ms |
| Heap Size | 6 MB | 5 MB |
Monitoring During Tests
Debug Log Analysis:
- Enable debug logs for running user
- Execute flow
- Review logs for
LIMIT_USAGE_FOR_NS
Key Log Entries:
LIMIT_USAGE_FOR_NS|namespace||SOQL queries|15/100
LIMIT_USAGE_FOR_NS|namespace||DML statements|5/150
LIMIT_USAGE_FOR_NS|namespace||CPU time|1234/10000
Governor Limit Prevention
If approaching limits:
- SOQL: Consolidate queries, add filters
- DML: Batch operations, reduce elements
- CPU: Simplify formulas, reduce loops
- Heap: Process in smaller batches
<a id="9-post-deployment-verification"></a>
9. Post-Deployment Verification
Immediate Checks (Within 1 Hour)
Check Flow Status: Setup → Process Automation → Flows
- Verify flow is Active (if intended)
- Verify correct version is active
Review Debug Logs: Developer Console → Debug Logs
- Check for unexpected errors
- Verify expected execution paths
Monitor Flow Interviews: Setup → Process Automation → Paused Flow Interviews
- No unexpected paused interviews
Check Errors: Setup → Process Automation → Flow Errors
- No new errors from the deployed flow
Short-Term Monitoring (First 24-48 Hours)
- Monitor for user-reported issues
- Check batch job completions (scheduled flows)
- Review error email notifications
- Verify integrations still working
Query Flow Errors
sf data query --query "SELECT Id, ElementApiName, ErrorMessage, FlowVersionId, InterviewGuid FROM FlowInterviewLogEntry WHERE CreatedDate = TODAY ORDER BY CreatedDate DESC LIMIT 20" --target-org [org]
Quick Reference Commands
# Deploy and test
sf project deploy start --source-dir force-app --target-org sandbox
# Query flow interviews
sf data query --query "SELECT Id, Status FROM FlowInterview WHERE FlowDeveloperName='MyFlow' LIMIT 10" --target-org sandbox
# Check scheduled jobs
sf data query --query "SELECT Id, CronJobDetail.Name, State, NextFireTime FROM CronTrigger" --target-org sandbox
# Authenticate as different user (sf org login user does not exist)
sf org login web --alias test-user-org
# Note: To test as different users, authenticate separate orgs or use sf org login jwt
Flow Test CLI Commands
Run Flow Tests
sf flow run testis a first-class CLI command for running Flow tests (available in sf CLI v2.122.6+).
# Run all Flow tests
sf flow run test -o TARGET_ORG --json
# Run with code coverage
sf flow run test -o TARGET_ORG --code-coverage --json
# Run specific test classes
sf flow run test --class-names MyFlowTest -o TARGET_ORG --json
# Synchronous execution (waits for completion)
sf flow run test -o TARGET_ORG --synchronous --json
Combined Apex + Flow Test Runner
sf logic run testruns both Apex and Flow tests in a single command — useful for comprehensive CI/CD test suites.
# Run combined Apex + Flow tests
sf logic run test -o TARGET_ORG --json
# Check results
sf logic get test --test-run-id <id> -o TARGET_ORG --json
Related Documentation
- Flow Best Practices - Design patterns and standards
- Testing Checklist - Quick reference checklist
- Governance Checklist - Security and compliance
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Transform vs Loop: A Decision Guide
When processing collections in Salesforce Flow, choosing between Transform and Loop elements can significantly impact both performance and maintainability. This guide provides clear decision criteria and best practices.
Quick Decision Matrix
┌─────────────────────────────────────────────────────────────────────────┐
│ TRANSFORM vs LOOP DECISION MATRIX │
├───────────────────────────────┬─────────────────────────────────────────┤
│ USE TRANSFORM │ USE LOOP │
├───────────────────────────────┼─────────────────────────────────────────┤
│ Mapping one collection to │ IF/ELSE logic per record │
│ another │ Different records need different paths │
│ Bulk field assignments │ Counters, flags, multi-step calcs │
│ Simple formula calculations │ Business rules vary per record │
│ Preparing records for DML │ Need to track state across iterations │
│ Fewer elements, cleaner flows │ Complex conditional transformations │
└───────────────────────────────┴─────────────────────────────────────────┘
Simple Rule to Remember:
- Shaping data → Use Transform (30-50% faster)
- Making decisions per record → Use Loop
When Transform is the Right Choice
Transform is ideal when you need to:
1. Map One Collection to Another
Converting a collection of one record type to another (e.g., Contacts → Opportunity Contact Roles).
✅ GOOD: Get Contacts → Transform → Create Opportunity Contact Roles
❌ BAD: Get Contacts → Loop → Assignment → Create Records (per iteration)
2. Bulk Field Assignments
Assigning the same field values across all records in a collection.
Example: Set Status = "Processed" for all records
Transform handles this in a single server-side operation.
3. Simple Calculations Using Formulas
Transform supports formulas for generating dynamic values during mapping.
Example: Calculate FullName from FirstName + ' ' + LastName
4. Prepare Records for Create/Update Operations
Building a collection of records to insert or update.
Example: Map Account fields to new Case records before bulk insert
5. Reduce Flow Elements
Transform consolidates what would be Loop + Assignment into a single element, making flows cleaner and easier to maintain.
When You Still Need a Loop
Loop is required when:
1. IF/ELSE Logic Per Record
Different records need different processing paths.
Example:
- If Amount > 10000 → High priority
- If Amount > 5000 → Medium priority
- Else → Low priority
2. Counters, Flags, or Multi-Step Calculations
You need to maintain state across iterations.
Example: Count how many records meet certain criteria
Track running totals
Build comma-separated lists
3. Business Rules Vary Per Record
Each record may follow a different logic path based on its values.
Example: Route leads to different queues based on State + Industry
4. Complex Conditional Transformations
When the transformation logic itself is conditional and complex.
Example: If record has parent → use parent's values
If orphan → use defaults
If flagged → skip entirely
Performance Comparison
| Metric | Transform | Loop + Assignment |
|---|---|---|
| Processing Model | Server-side bulk | Client-side iteration |
| Speed | 30-50% faster | Baseline |
| CPU Time | Lower | Higher |
| DML Statements | No change | No change |
| Flow Elements | 1 element | 2+ elements |
| Maintainability | Simpler | More complex |
Why Transform is Faster
Transform processes the entire collection as a single server-side operation, while Loop iterates through each record individually. For large collections (100+ records), this difference becomes significant.
Visual Comparison: Before and After
BAD Pattern: Loop for Simple Mapping
┌─────────────────────────────────────────────────────────────────────────┐
│ ❌ ANTI-PATTERN: Using Loop for Simple Field Mapping │
└─────────────────────────────────────────────────────────────────────────┘
┌──────────────────┐
│ Get Records │ Query Contacts
│ (All Contacts) │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Loop │ Iterate through each Contact
│ (Contact Loop) │◄──────────────────────────────┐
└────────┬─────────┘ │
│ For Each │
▼ │
┌──────────────────┐ │
│ Assignment │ Map Contact fields to │
│ (Map Fields) │ OpportunityContactRole │
└────────┬─────────┘ │
│ │
▼ │
┌──────────────────┐ │
│ Add to Collection│ Build output collection │
└────────┬─────────┘ │
│ After Last ─────────────────────────────┘
▼
┌──────────────────┐
│ Create Records │ Insert all OCRs
└──────────────────┘
Problem: 4 elements, client-side iteration, slower
GOOD Pattern: Transform for Simple Mapping
┌─────────────────────────────────────────────────────────────────────────┐
│ ✅ BEST PRACTICE: Using Transform for Field Mapping │
└─────────────────────────────────────────────────────────────────────────┘
┌──────────────────┐
│ Get Records │ Query Contacts
│ (All Contacts) │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Transform │ Map Contact → OpportunityContactRole
│ (Map to OCR) │ (Server-side bulk operation)
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Create Records │ Insert all OCRs
└──────────────────┘
Benefits: 3 elements, server-side processing, 30-50% faster
Transform XML Structure Reference
Important: Create Transform elements in Flow Builder UI, then deploy. The XML structure is complex and error-prone to hand-write.
Basic Structure
<transforms>
<name>Transform_Contacts_To_OCR</name>
<label>Transform Contacts to Opportunity Contact Roles</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Create_OCR_Records</targetReference>
</connector>
<!-- Input: collection of source records -->
<inputVariable>col_Contacts</inputVariable>
<!-- Output: collection of target records -->
<outputVariable>col_OpportunityContactRoles</outputVariable>
<!-- Field mappings with optional formulas -->
<transformValueActions>
<transformValueActionType>Map</transformValueActionType>
<inputReference>col_Contacts.ContactId</inputReference>
<outputReference>col_OpportunityContactRoles.ContactId</outputReference>
</transformValueActions>
<transformValueActions>
<transformValueActionType>Map</transformValueActionType>
<inputReference>var_OpportunityId</inputReference>
<outputReference>col_OpportunityContactRoles.OpportunityId</outputReference>
</transformValueActions>
<transformValueActions>
<transformValueActionType>Formula</transformValueActionType>
<formula>"Primary"</formula>
<outputReference>col_OpportunityContactRoles.Role</outputReference>
</transformValueActions>
</transforms>
Key Elements
| Element | Purpose |
|---|---|
inputVariable |
Source collection to transform |
outputVariable |
Target collection (output) |
transformValueActions |
Individual field mappings |
transformValueActionType |
Map (direct copy) or Formula (calculated) |
inputReference |
Source field path |
outputReference |
Target field path |
formula |
Formula expression (when type is Formula) |
Testing Transform Elements
1. Flow Builder Debug Mode
Step-by-Step:
1. Open your flow in Flow Builder
2. Click the "Debug" button in the toolbar
3. Configure debug inputs:
- Provide a sample collection (or create test records)
- Set any required input variables
4. Run the debug
5. Inspect the Transform element output:
- Verify field mappings are correct
- Check formula calculations
- Confirm collection size matches input
2. Apex Test Class Approach
@isTest
private class TransformFlowTest {
@isTest
static void testTransformMapsFieldsCorrectly() {
// Setup: Create source records
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(
FirstName = 'Test' + i,
LastName = 'Contact' + i,
Email = 'test' + i + '@example.com'
));
}
insert contacts;
// Create parent Opportunity
Opportunity opp = new Opportunity(
Name = 'Test Opp',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert opp;
// Execute: Run the Transform flow
Test.startTest();
Map<String, Object> inputs = new Map<String, Object>{
'inp_Contacts' => contacts,
'inp_OpportunityId' => opp.Id
};
Flow.Interview.Transform_Contact_To_OCR flow =
new Flow.Interview.Transform_Contact_To_OCR(inputs);
flow.start();
Test.stopTest();
// Verify: Check transformed records were created
List<OpportunityContactRole> ocrs = [
SELECT Id, ContactId, OpportunityId, Role
FROM OpportunityContactRole
WHERE OpportunityId = :opp.Id
];
System.assertEquals(200, ocrs.size(), 'All contacts should be mapped');
for (OpportunityContactRole ocr : ocrs) {
System.assertNotEquals(null, ocr.ContactId, 'ContactId should be mapped');
System.assertEquals(opp.Id, ocr.OpportunityId, 'OpportunityId should be set');
}
}
@isTest
static void testTransformPerformance() {
// Setup: Create 250 records (exceeds batch boundary)
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 250; i++) {
contacts.add(new Contact(
FirstName = 'Perf' + i,
LastName = 'Test' + i
));
}
insert contacts;
Opportunity opp = new Opportunity(
Name = 'Perf Test',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
insert opp;
// Execute and measure
Test.startTest();
Integer cpuBefore = Limits.getCpuTime();
Map<String, Object> inputs = new Map<String, Object>{
'inp_Contacts' => contacts,
'inp_OpportunityId' => opp.Id
};
Flow.Interview.Transform_Contact_To_OCR flow =
new Flow.Interview.Transform_Contact_To_OCR(inputs);
flow.start();
Integer cpuAfter = Limits.getCpuTime();
Test.stopTest();
// Assert: Transform should be efficient
Integer cpuUsed = cpuAfter - cpuBefore;
System.assert(cpuUsed < 5000,
'Transform should use minimal CPU. Used: ' + cpuUsed + 'ms');
}
}
3. CLI Performance Comparison
# Enable debug logging
sf apex tail log --color
# Run Transform flow via anonymous Apex
sf apex run -f scripts/run-transform-flow.apex
# Run equivalent Loop flow for comparison
sf apex run -f scripts/run-loop-flow.apex
# Compare CPU_TIME in debug logs
# Transform should show ~30-50% lower CPU_TIME
Sample Anonymous Apex (scripts/run-transform-flow.apex)
// Query source records
List<Contact> contacts = [SELECT Id, FirstName, LastName, Email FROM Contact LIMIT 200];
// Get target Opportunity
Opportunity opp = [SELECT Id FROM Opportunity LIMIT 1];
// Run Transform flow
Map<String, Object> inputs = new Map<String, Object>{
'inp_Contacts' => contacts,
'inp_OpportunityId' => opp.Id
};
Flow.Interview flow = Flow.Interview.createInterview('Transform_Contact_To_OCR', inputs);
flow.start();
System.debug('Transform completed. CPU Time: ' + Limits.getCpuTime() + 'ms');
Migration Checklist: Loop to Transform
If you have existing flows using Loop for simple field mapping, consider migrating:
- Identify Loop elements that only do field assignment (no decisions)
- Verify no counters, flags, or state tracking is needed
- Create equivalent Transform element in Flow Builder UI
- Test with same data set
- Compare debug output for correctness
- Compare CPU time for performance gain
- Replace Loop + Assignment with single Transform
- Validate and deploy
Common Mistakes to Avoid
1. Using Transform for Conditional Logic
❌ WRONG: Trying to add IF/ELSE inside Transform
Transform doesn't support per-record branching.
✅ RIGHT: Use Loop + Decision for conditional processing.
2. Ignoring the UI Recommendation
❌ WRONG: Hand-writing Transform XML
The XML structure is complex with strict ordering requirements.
✅ RIGHT: Always create Transform in Flow Builder, then deploy.
3. Over-Optimizing Simple Flows
❌ WRONG: Converting every Loop to Transform
Some flows process very small collections where optimization doesn't matter.
✅ RIGHT: Focus on loops processing 50+ records regularly.
Related Documentation
- Loop Pattern Template - When Loop is the right choice
- Transform Pattern Template - Reference XML structure
- Flow Best Practices - General optimization guidelines
- Governance Checklist - Pre-deployment validation
Attribution
This guide was inspired by content shared by:
- Jalumchi Akpoke - Transform vs Loop decision pattern visualization
- Shubham Bhardwaj - Original YouTube video on Transform efficiency
See CREDITS.md for full attribution.
<!-- Modified by Automation Skills on 2026-11-24: relative links to files that were not copied now point to the original repository. -->Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Flow-LWC-Apex Triangle: Flow Perspective
The Triangle Architecture is a foundational Salesforce pattern where Flow, LWC, and Apex work together. This guide focuses on the Flow role as the orchestrator.
Architecture Overview
┌─────────────────────────────────────┐
│ FLOW ◀── YOU ARE HERE
│ (Orchestrator) │
│ │
│ • Process Logic │
│ • User Experience │
│ • Variable Management │
└───────────────┬─────────────────────┘
│
┌──────────────────────────┼──────────────────────────┐
│ │ │
│ screens │ actionCalls │
│ <componentInstance> │ actionType="apex" │
│ │ │
▼ ▼ ▲
┌─────────────────────────┐ ┌─────────────────────────┐ │
│ LWC │ │ APEX │ │
│ (UI Component) │───▶│ (Business Logic) │─────────┘
│ │ │ │
│ • Rich UI/UX │ │ • @InvocableMethod │
│ • User Interaction │ │ • @AuraEnabled │
│ • FlowAttribute │ │ • Complex Logic │
│ ChangeEvent │ │ • DML Operations │
│ • FlowNavigation │ │ • Integration │
│ FinishEvent │ │ │
└─────────────────────────┘ └─────────────────────────┘
Flow's Role in the Triangle
| Communication Path | Flow XML Element | Direction |
|---|---|---|
| Flow → LWC | inputParameters in <screens> |
Push data to component |
| LWC → Flow | outputParameters in <screens> |
Receive from component |
| Flow → Apex | actionCalls with actionType="apex" |
Call Invocable |
| Apex → Flow | outputParameters in <actionCalls> |
Receive results |
Pattern 1: Flow Embedding LWC Screen Component
Use Case: Custom UI component for user selection within a guided Flow.
┌─────────┐ inputParameters ┌─────────┐
│ FLOW │ ─────────────────────▶ │ LWC │
│ Screen │ │Component│
│ │ ◀───────────────────── │ │
│ │ outputParameters │ │
└─────────┘ └─────────┘
Flow XML
<screens>
<name>Select_Record_Screen</name>
<label>Select Record</label>
<locationX>264</locationX>
<locationY>398</locationY>
<allowBack>true</allowBack>
<allowFinish>true</allowFinish>
<allowPause>false</allowPause>
<connector>
<targetReference>Process_Selection</targetReference>
</connector>
<fields>
<name>recordSelectorComponent</name>
<extensionName>c:recordSelector</extensionName>
<fieldType>ComponentInstance</fieldType>
<inputParameters>
<name>recordId</name>
<value>
<elementReference>var_ParentRecordId</elementReference>
</value>
</inputParameters>
<outputParameters>
<assignToReference>var_SelectedRecordId</assignToReference>
<name>selectedRecordId</name>
</outputParameters>
</fields>
</screens>
Variable Definitions
<variables>
<name>var_ParentRecordId</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>var_SelectedRecordId</name>
<dataType>String</dataType>
<isCollection>false</isCollection>
<isInput>false</isInput>
<isOutput>true</isOutput>
</variables>
Pattern 2: Flow Calling Apex Invocable
Use Case: Complex business logic, DML, or external integrations.
┌─────────┐ actionCalls ┌─────────┐
│ FLOW │ ───────────────▶ │ APEX │
│ │ inputParams │@Invocable│
│ │ ◀─────────────── │ Method │
│ │ outputParams │ │
└─────────┘ └─────────┘
Flow XML
<actionCalls>
<name>Process_Records</name>
<label>Process Records</label>
<locationX>440</locationX>
<locationY>518</locationY>
<actionName>RecordProcessor</actionName>
<actionType>apex</actionType>
<connector>
<targetReference>Show_Success</targetReference>
</connector>
<faultConnector>
<targetReference>Handle_Error</targetReference>
</faultConnector>
<inputParameters>
<name>recordId</name>
<value>
<elementReference>var_RecordId</elementReference>
</value>
</inputParameters>
<inputParameters>
<name>processType</name>
<value>
<stringValue>FULL</stringValue>
</value>
</inputParameters>
<outputParameters>
<assignToReference>var_IsSuccess</assignToReference>
<name>isSuccess</name>
</outputParameters>
<outputParameters>
<assignToReference>var_ProcessedId</assignToReference>
<name>processedId</name>
</outputParameters>
<outputParameters>
<assignToReference>var_ErrorMessage</assignToReference>
<name>errorMessage</name>
</outputParameters>
<storeOutputAutomatically>false</storeOutputAutomatically>
</actionCalls>
Fault Handling
<screens>
<name>Handle_Error</name>
<label>Error</label>
<locationX>660</locationX>
<locationY>638</locationY>
<fields>
<name>ErrorDisplay</name>
<fieldText><p><strong>An error occurred:</strong></p><p>{!$Flow.FaultMessage}</p></fieldText>
<fieldType>DisplayText</fieldType>
</fields>
</screens>
Pattern 3: Full Triangle Flow
Use Case: Complete solution combining LWC screens and Apex actions.
<?xml version="1.0" encoding="UTF-8"?>
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<label>Quote Builder Flow</label>
<processType>Flow</processType>
<status>Active</status>
<interviewLabel>Quote Builder {!$Flow.CurrentDateTime}</interviewLabel>
<!-- Start -->
<start>
<locationX>50</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Select_Products_Screen</targetReference>
</connector>
</start>
<!-- LWC Screen: Product Selection -->
<screens>
<name>Select_Products_Screen</name>
<label>Select Products</label>
<connector>
<targetReference>Calculate_Pricing_Apex</targetReference>
</connector>
<fields>
<name>productSelectorLWC</name>
<extensionName>c:productSelector</extensionName>
<fieldType>ComponentInstance</fieldType>
<inputParameters>
<name>accountId</name>
<value><elementReference>var_AccountId</elementReference></value>
</inputParameters>
<outputParameters>
<assignToReference>var_SelectedProductIds</assignToReference>
<name>selectedProducts</name>
</outputParameters>
</fields>
</screens>
<!-- Apex Action: Calculate Pricing -->
<actionCalls>
<name>Calculate_Pricing_Apex</name>
<actionName>PricingCalculator</actionName>
<actionType>apex</actionType>
<connector>
<targetReference>Review_Quote_Screen</targetReference>
</connector>
<faultConnector>
<targetReference>Pricing_Error_Screen</targetReference>
</faultConnector>
<inputParameters>
<name>productIds</name>
<value><elementReference>var_SelectedProductIds</elementReference></value>
</inputParameters>
<inputParameters>
<name>accountId</name>
<value><elementReference>var_AccountId</elementReference></value>
</inputParameters>
<outputParameters>
<assignToReference>var_QuoteLineItems</assignToReference>
<name>lineItems</name>
</outputParameters>
<outputParameters>
<assignToReference>var_TotalPrice</assignToReference>
<name>totalPrice</name>
</outputParameters>
</actionCalls>
<!-- LWC Screen: Review Quote -->
<screens>
<name>Review_Quote_Screen</name>
<label>Review Quote</label>
<connector>
<targetReference>Create_Quote_Record</targetReference>
</connector>
<fields>
<name>quoteReviewLWC</name>
<extensionName>c:quoteReview</extensionName>
<fieldType>ComponentInstance</fieldType>
<inputParameters>
<name>lineItems</name>
<value><elementReference>var_QuoteLineItems</elementReference></value>
</inputParameters>
<inputParameters>
<name>totalPrice</name>
<value><elementReference>var_TotalPrice</elementReference></value>
</inputParameters>
<outputParameters>
<assignToReference>var_ApprovedForSubmit</assignToReference>
<name>isApproved</name>
</outputParameters>
</fields>
</screens>
<!-- Variables -->
<variables>
<name>var_AccountId</name>
<dataType>String</dataType>
<isInput>true</isInput>
</variables>
<variables>
<name>var_SelectedProductIds</name>
<dataType>String</dataType>
<isCollection>true</isCollection>
</variables>
<variables>
<name>var_QuoteLineItems</name>
<dataType>Apex</dataType>
<apexClass>QuoteLineItemWrapper</apexClass>
<isCollection>true</isCollection>
</variables>
<variables>
<name>var_TotalPrice</name>
<dataType>Currency</dataType>
</variables>
</Flow>
Testing Flow with Apex
@isTest
private class QuoteBuilderFlowTest {
@isTest
static void testFlowWithApexIntegration() {
// Setup test data
Account acc = new Account(Name = 'Test Account');
insert acc;
Product2 prod = new Product2(Name = 'Test Product', IsActive = true);
insert prod;
// Flow inputs
Map<String, Object> inputs = new Map<String, Object>{
'var_AccountId' => acc.Id
};
Test.startTest();
// Create and run Flow interview
Flow.Interview flow = Flow.Interview.createInterview(
'Quote_Builder_Flow',
inputs
);
flow.start();
Test.stopTest();
// Verify Flow outputs
Object totalPrice = flow.getVariableValue('var_TotalPrice');
System.assertNotEquals(null, totalPrice, 'Total price should be calculated');
}
}
Deployment Order
When deploying integrated triangle solutions:
1. APEX CLASSES
└── @InvocableMethod classes
└── @AuraEnabled controllers
2. LWC COMPONENTS
└── meta.xml with targets
└── JavaScript with Flow imports
3. FLOWS ← Deploy LAST
└── Reference deployed Apex classes
└── Reference deployed LWC components
Decision Matrix: When to Use Each Approach
| Scenario | Primary | Supporting | Why |
|---|---|---|---|
| Simple record selection | LWC | - | Rich UI, immediate feedback |
| Complex multi-step process | Flow | Apex, LWC | Orchestration strength |
| Bulk data processing | Apex | - | Governor limit handling |
| Custom UI in guided process | Flow | LWC | Best of both |
| External API integration | Apex | Flow wrapper | Authentication, callouts |
| Admin-maintainable logic | Flow | Apex for complex ops | Low-code primary |
| User-facing wizard | Flow + LWC | Apex | Complete solution |
Common Anti-Patterns
| Anti-Pattern | Problem | Solution |
|---|---|---|
| No faultConnector on Apex actions | Unhandled exceptions crash Flow | Always add fault path |
| Hardcoded IDs in Flow | Environment-specific failures | Use Custom Metadata or variables |
| Missing outputParameters | Apex results not available | Map all needed outputs |
| LWC without outputParameters | Component outputs ignored | Add outputParameters mapping |
| Skipping validation before Apex | Invalid data causes errors | Add decision elements |
Related Documentation
| Topic | Location |
|---|---|
| Apex action template | sf-flow/assets/apex-action-template.xml |
| Screen Flow with LWC | sf-flow/assets/screen-flow-with-lwc.xml |
| LWC integration guide | sf-flow/references/lwc-integration-guide.md |
| Apex triangle perspective | sf-apex/references/triangle-pattern.md |
| LWC triangle perspective | sf-lwc/references/triangle-pattern.md |
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Salesforce Flow Wait Element Patterns
Comprehensive guide to using Wait elements in Salesforce Flows for time-based and condition-based pausing.
Flow Type Compatibility
Wait elements have strict flow type requirements:
| Flow Type | Wait Supported? | Notes |
|---|---|---|
| Autolaunched Flow | ✅ Yes | Primary use case |
| Scheduled Flow | ✅ Yes | Often combined with scheduling |
| Orchestration | ✅ Yes | For complex multi-step processes |
| Screen Flow | ❌ No | Cannot pause user sessions |
| Record-Triggered Flow | ❌ No | Must complete synchronously |
| Platform Event Flow | ❌ No | Event-driven, no waiting |
Key Insight: If you need wait behavior in a Record-Triggered Flow, call an Autolaunched subflow that contains the Wait element.
Three Wait Element Types
1. Wait for Amount of Time (Duration-Based)
Pauses flow execution for a fixed duration.
Use Cases:
- Send follow-up email 24 hours after form submission
- Escalate case if not resolved within 48 hours
- Wait 7 days before survey request
XML Structure:
<waits>
<name>Wait_7_Days</name>
<label>Wait 7 Days</label>
<waitEvents>
<name>Duration_Complete</name>
<eventType>AlarmEvent</eventType>
<inputParameters>
<name>AlarmTime</name>
<value>
<elementReference>$Flow.CurrentDateTime</elementReference>
</value>
</inputParameters>
<inputParameters>
<name>TimeOffset</name>
<value>
<numberValue>7.0</numberValue>
</value>
</inputParameters>
<inputParameters>
<name>TimeOffsetUnit</name>
<value>
<stringValue>Days</stringValue>
</value>
</inputParameters>
<connector>
<targetReference>Next_Element</targetReference>
</connector>
</waitEvents>
</waits>
TimeOffsetUnit Options:
MinutesHoursDaysMonths
2. Wait Until Date (Date-Based)
Pauses until a specific date/time is reached.
Use Cases:
- Resume on contract expiration date
- Notify before subscription renewal
- Trigger on scheduled meeting time
XML Structure:
<waits>
<name>Wait_Until_Renewal</name>
<label>Wait Until Renewal Date</label>
<waitEvents>
<name>Date_Reached</name>
<eventType>DateRefAlarmEvent</eventType>
<inputParameters>
<name>DateTime</name>
<value>
<elementReference>var_RenewalDate</elementReference>
</value>
</inputParameters>
<connector>
<targetReference>Send_Renewal_Reminder</targetReference>
</connector>
</waitEvents>
</waits>
Pro Tip: Use a formula to calculate the target date:
<formulas>
<name>formula_RenewalReminder</name>
<dataType>DateTime</dataType>
<!-- 30 days before renewal -->
<expression>{!rec_Contract.EndDate} - 30</expression>
</formulas>
3. Wait for Conditions (Condition-Based)
Pauses until a field meets specified criteria OR timeout expires.
Use Cases:
- Resume when Case Status changes to 'Closed'
- Resume when Approval Status is 'Approved'
- Resume when Payment is 'Received'
XML Structure:
<waits>
<name>Wait_For_Approval</name>
<label>Wait for Approval</label>
<defaultConnector>
<targetReference>Handle_Timeout</targetReference>
</defaultConnector>
<defaultConnectorLabel>Max Wait Exceeded</defaultConnectorLabel>
<waitEvents>
<name>Approval_Received</name>
<conditionLogic>and</conditionLogic>
<conditions>
<leftValueReference>rec_Request.Status__c</leftValueReference>
<operator>EqualTo</operator>
<rightValue>
<stringValue>Approved</stringValue>
</rightValue>
</conditions>
<eventType>AlarmEvent</eventType>
<inputParameters>
<name>AlarmTime</name>
<value>
<elementReference>$Flow.CurrentDateTime</elementReference>
</value>
</inputParameters>
<inputParameters>
<name>TimeOffset</name>
<value>
<numberValue>30.0</numberValue>
</value>
</inputParameters>
<inputParameters>
<name>TimeOffsetUnit</name>
<value>
<stringValue>Days</stringValue>
</value>
</inputParameters>
<connector>
<targetReference>Process_Approved_Request</targetReference>
</connector>
<label>Approved</label>
</waitEvents>
</waits>
Warning: Condition-based waits are complex. Consider Platform Events for simpler event-driven patterns.
Best Practices
1. Always Handle Timeout Paths
<waits>
<name>Wait_With_Timeout</name>
<defaultConnector>
<targetReference>Handle_Timeout</targetReference>
</defaultConnector>
<defaultConnectorLabel>Timeout - No Response</defaultConnectorLabel>
<!-- waitEvents... -->
</waits>
2. Consider Governor Limits
Waiting flows consume org resources:
- Each paused flow interview counts against limits
- Long waits with many instances can accumulate
- Monitor with Setup → Flows → Paused and Waiting Interviews
3. Use Variables for Dynamic Durations
<variables>
<name>var_WaitDays</name>
<dataType>Number</dataType>
<value>
<numberValue>7.0</numberValue>
</value>
</variables>
<!-- Reference in Wait -->
<inputParameters>
<name>TimeOffset</name>
<value>
<elementReference>var_WaitDays</elementReference>
</value>
</inputParameters>
4. Test with Shorter Durations
In sandbox environments:
- Use minutes instead of days for testing
- Verify timeout paths work correctly
- Check debug logs for wait behavior
5. Document Wait Logic
Add XML comments explaining:
- Why this duration was chosen
- What happens on timeout
- Business context for the wait
<!--
Wait 7 days for customer response.
Business Rule: BR-2024-015 - Follow-up SLA
Timeout Action: Escalate to manager
-->
<waits>
<name>Wait_Customer_Response</name>
<!-- ... -->
</waits>
Common Patterns
Follow-Up Email Pattern
Start
↓
Create Case → Wait 24 Hours → Check Status → (If Open) → Send Follow-Up
↓
(If Closed) → End
Escalation Ladder Pattern
Start
↓
Create Task → Wait 2 Days → Not Complete? → Escalate to Lead
↓
Wait 2 Days → Not Complete? → Escalate to Manager
↓
Wait 1 Day → Auto-Close with Note
Approval Wait Pattern
Start
↓
Submit for Approval → Wait for Approval (30 day max)
↓ ↓
(Approved) (Timeout)
↓ ↓
Process Request Notify Submitter
Platform Events vs. Wait for Conditions
Consider Platform Events when:
| Scenario | Use Wait | Use Platform Event |
|---|---|---|
| Fixed time delay | ✅ | ❌ |
| Wait for date | ✅ | ❌ |
| External system callback | ❌ | ✅ |
| Real-time field change | ❌ | ✅ |
| Complex event correlation | ❌ | ✅ |
| Simple status check | ✅ | ❌ |
Platform Event Advantage: Immediate response when event fires, no polling delay.
Wait Advantage: Simpler setup, no Platform Event definition required.
Troubleshooting
Paused Interview Not Resuming
- Check interview status in Setup → Flows → Paused and Waiting Interviews
- Verify target date hasn't passed (for Date-based waits)
- Check condition field values match expected criteria
- Review debug logs for errors during resume
Too Many Paused Interviews
- Add timeout paths to prevent indefinite waits
- Consider batch cleanup flow for stale interviews
- Reduce wait durations where possible
- Use
Database.deleteAsync()in Apex for cleanup
Performance Issues
- Avoid Wait elements in high-volume flows
- Consider Platform Events for real-time needs
- Use Scheduled Flows instead of Wait for batch operations
Related Templates
sf-flow/assets/wait-template.xml- All three wait patterns with examplessf-flow/assets/platform-event-flow-template.xml- Event-driven alternativesf-flow/assets/scheduled-flow-template.xml- Scheduled batch processing
Open this reference as its own page
<!-- Parent: sf-flow/SKILL.md -->Salesforce Flow XML Metadata Gotchas
Critical XML metadata constraints and known issues when deploying flows via Metadata API.
storeOutputAutomatically Data Leak Risk (v2.0.0)
⚠️ SECURITY WARNING: When storeOutputAutomatically="true" in recordLookups, ALL fields are retrieved and stored.
Risks
- Data Leak: Sensitive fields (SSN, salary, etc.) may be exposed unintentionally
- Performance: Large objects with many fields impact query performance
- Screen Flow Exposure: In screen flows, external users could access all data
Recommended Pattern
Always specify only the fields you need:
<recordLookups>
<name>Get_Account</name>
<!-- Specify exact fields needed -->
<queriedFields>Id</queriedFields>
<queriedFields>Name</queriedFields>
<queriedFields>Industry</queriedFields>
<!-- Store in explicit variable -->
<outputReference>rec_Account</outputReference>
</recordLookups>
Avoid:
<recordLookups>
<name>Get_Account</name>
<!-- Retrieves ALL fields - security risk! -->
<storeOutputAutomatically>true</storeOutputAutomatically>
</recordLookups>
Relationship Fields Not Supported in recordLookups (CRITICAL)
⚠️ DEPLOYMENT BLOCKER: Flow's Get Records (recordLookups) CANNOT query parent relationship fields.
What Doesn't Work
<!-- ❌ THIS WILL FAIL DEPLOYMENT -->
<recordLookups>
<name>Get_User</name>
<object>User</object>
<queriedFields>Id</queriedFields>
<queriedFields>Name</queriedFields>
<queriedFields>Manager.Name</queriedFields> <!-- FAILS! -->
</recordLookups>
Error: field integrity exception: unknown (The field "Manager.Name" for the object "User" doesn't exist.)
Why It Fails
- Flow's recordLookups only supports direct fields on the queried object
- Parent relationship traversal (dot notation like
Parent.Field) is NOT supported - This is different from SOQL in Apex which supports relationship queries
Fields That WON'T Work
| Object | Invalid Field | Error |
|---|---|---|
| User | Manager.Name |
Manager.Name doesn't exist |
| Contact | Account.Name |
Account.Name doesn't exist |
| Case | Account.Owner.Email |
Account.Owner.Email doesn't exist |
| Opportunity | Account.Industry |
Account.Industry doesn't exist |
Correct Solution: Two-Step Query
<!-- Step 1: Get the child record with lookup ID -->
<recordLookups>
<name>Get_User</name>
<object>User</object>
<queriedFields>Id</queriedFields>
<queriedFields>Name</queriedFields>
<queriedFields>ManagerId</queriedFields> <!-- ✅ Get the ID only -->
<outputReference>rec_User</outputReference>
</recordLookups>
<!-- Step 2: Query parent record using the lookup ID -->
<recordLookups>
<name>Get_Manager</name>
<object>User</object>
<filters>
<field>Id</field>
<operator>EqualTo</operator>
<value>
<elementReference>rec_User.ManagerId</elementReference>
</value>
</filters>
<queriedFields>Id</queriedFields>
<queriedFields>Name</queriedFields>
<outputReference>rec_Manager</outputReference>
</recordLookups>
Flow Routing
Ensure your flow checks for null before using the parent record:
<decisions>
<name>Check_Manager_Exists</name>
<rules>
<conditions>
<leftValueReference>rec_Manager</leftValueReference>
<operator>IsNull</operator>
<rightValue><booleanValue>false</booleanValue></rightValue>
</conditions>
</rules>
</decisions>
$Record vs $Record__c Confusion (Record-Triggered Flows)
⚠️ COMMON MISTAKE: Confusing Flow's $Record with Process Builder's $Record__c.
What's the Difference?
| Variable | Context | Usage |
|---|---|---|
$Record |
Flow (Record-Triggered) | Single record that triggered the flow |
$Record__c |
Process Builder | Collection of records in trigger batch |
The Mistake
Trying to create a loop over $Record__c in a Flow:
<!-- ❌ THIS DOES NOT EXIST IN FLOWS -->
<loops>
<collectionReference>$Record__c</collectionReference> <!-- INVALID! -->
</loops>
Why This Happens
- Process Builder used
$Record__cto represent the batch of triggering records - Developers migrating from Process Builder assume Flows work the same way
- In Flows,
$Recordis always a single record, not a collection - The platform handles bulk batching automatically
Correct Approach in Record-Triggered Flows
Use $Record directly without loops:
<!-- ✅ CORRECT: Direct access to triggered record -->
<decisions>
<conditions>
<leftValueReference>$Record.StageName</leftValueReference>
<operator>EqualTo</operator>
<rightValue><stringValue>Closed Won</stringValue></rightValue>
</conditions>
</decisions>
<!-- ✅ Build task using $Record fields -->
<assignments>
<assignmentItems>
<assignToReference>rec_Task.WhatId</assignToReference>
<value><elementReference>$Record.Id</elementReference></value>
</assignmentItems>
</assignments>
When You DO Need Loops
Only when processing related records, not the triggered record:
<!-- ✅ CORRECT: Loop over RELATED records -->
<recordLookups>
<filters>
<field>AccountId</field>
<value><elementReference>$Record.AccountId</elementReference></value>
</filters>
<outputReference>col_RelatedContacts</outputReference>
</recordLookups>
<loops>
<collectionReference>col_RelatedContacts</collectionReference> <!-- ✅ Valid -->
</loops>
recordLookups Conflicts
NEVER use both <storeOutputAutomatically> AND <outputReference> together.
Choose ONE approach:
<!-- Option 1: Auto-store (creates variable automatically) - NOT RECOMMENDED -->
<storeOutputAutomatically>true</storeOutputAutomatically>
<!-- Option 2: Explicit variable - RECOMMENDED -->
<outputReference>rec_AccountRecord</outputReference>
Element Ordering in recordLookups
Elements must follow this order:
<name>2.<label>3.<locationX>4.<locationY>5.<assignNullValuesIfNoRecordsFound>6.<connector>7.<filterLogic>8.<filters>9.<getFirstRecordOnly>10.<object>11.<outputReference>OR<storeOutputAutomatically>12.<queriedFields>
Transform Element
Recommendation: Create Transform elements in Flow Builder UI, then deploy - do NOT hand-write.
Issues with hand-written Transform:
- Complex nested XML structure with strict ordering
inputReferenceplacement varies by context- Multiple conflicting rules in Metadata API
Subflow Elements: What Works and What Doesn't
Record-triggered flows CAN call subflows via XML deployment (confirmed API 66.0, Spring '26).
Working <subflows> Example
<subflows>
<name>Call_Validation_Subflow</name>
<label>Call Validation Subflow</label>
<locationX>0</locationX>
<locationY>0</locationY>
<connector>
<targetReference>Next_Element</targetReference>
</connector>
<flowName>Validation_Subflow</flowName>
<inputAssignments>
<name>recordId</name>
<value>
<elementReference>$Record.Id</elementReference>
</value>
</inputAssignments>
<outputAssignments>
<assignToReference>validationResult</assignToReference>
<name>isValid</name>
</outputAssignments>
</subflows>
<faultConnector> Is NOT Valid on <subflows>
Adding a <faultConnector> to a <subflows> element causes a deployment error:
Error: The "faultConnector" field should not be set for "subflows" elements.
Valid <faultConnector> targets (elements that DO support fault paths):
<actionCalls>— Apex invocable actions, external services<recordCreates>— DML create operations<recordUpdates>— DML update operations<recordDeletes>— DML delete operations
Correct Pattern: Handle Faults Inside the Subflow
Instead of adding a fault connector on the <subflows> element, handle faults within the subflow itself and surface errors via output variables:
- Inside the subflow: wrap DML/action calls with fault connectors
- On fault: set an output variable (e.g.,
errorMessage) with the error details - In the parent flow: check the output variable after the subflow call and branch accordingly
Fault Connectors Cannot Self-Reference (CRITICAL)
⚠️ DEPLOYMENT BLOCKER: An element CANNOT have a fault connector pointing to itself.
What Doesn't Work
<!-- ❌ THIS WILL FAIL DEPLOYMENT -->
<recordUpdates>
<name>Update_Account</name>
<label>Update Account</label>
<connector>
<targetReference>Next_Element</targetReference>
</connector>
<faultConnector>
<targetReference>Update_Account</targetReference> <!-- FAILS! Self-reference -->
</faultConnector>
<!-- ... -->
</recordUpdates>
Error: The element "Update_Account" cannot be connected to itself.
Why This Matters
- Self-referencing fault connectors would create infinite loops on failure
- Salesforce validates this during deployment and blocks it
- This applies to ALL connector types (faultConnector, connector, nextValueConnector, etc.)
Correct Fault Handling Patterns
Option 1: Route to dedicated error handler:
<recordUpdates>
<name>Update_Account</name>
<faultConnector>
<targetReference>Handle_Update_Error</targetReference> <!-- ✅ Different element -->
</faultConnector>
</recordUpdates>
<assignments>
<name>Handle_Update_Error</name>
<!-- Log error, set flag, etc. -->
</assignments>
Option 2: Route to error logging assignment:
<recordUpdates>
<name>Update_Account</name>
<faultConnector>
<targetReference>Log_Error_And_Continue</targetReference> <!-- ✅ -->
</faultConnector>
</recordUpdates>
Option 3: Omit fault connector (flow will terminate on error):
<recordUpdates>
<name>Update_Account</name>
<connector>
<targetReference>Next_Element</targetReference>
</connector>
<!-- No faultConnector - flow terminates on failure -->
</recordUpdates>
Best Practice
- Always route fault connectors to a dedicated error handling element
- Use an assignment to capture
{!$Flow.FaultMessage}before logging - Consider whether the flow should continue or terminate on failure
Root-Level Element Ordering (CRITICAL)
Salesforce Metadata API requires strict alphabetical ordering at root level.
Complete Element Type List (Alphabetical Order)
All elements of the same type MUST be grouped together. You CANNOT have elements of one type scattered across the file.
1. <apiVersion>
2. <assignments> ← ALL assignments together
3. <constants>
4. <decisions> ← ALL decisions together
5. <description>
6. <environments>
7. <formulas>
8. <interviewLabel>
9. <label>
10. <loops> ← ALL loops together
11. <processMetadataValues>
12. <processType>
13. <recordCreates> ← ALL recordCreates together
14. <recordDeletes> ← ALL recordDeletes together
15. <recordLookups> ← ALL recordLookups together
16. <recordUpdates> ← ALL recordUpdates together
17. <runInMode>
18. <screens> ← ALL screens together
19. <start>
20. <status>
21. <subflows> ← ALL subflows together
22. <textTemplates>
23. <variables> ← ALL variables together
24. <waits>
The Grouping Rule (CRITICAL)
Wrong - Assignment after loops section:
<assignments>
<name>Set_Initial_Values</name>
<!-- ... -->
</assignments>
<loops>
<name>Loop_Contacts</name>
<!-- ... -->
</loops>
<assignments> <!-- ❌ FAILS: Can't have assignments after loops! -->
<name>Increment_Counter</name>
<!-- ... -->
</assignments>
Error: Element assignments is duplicated at this location in type Flow
Correct - All assignments together:
<assignments> <!-- ✅ All assignments grouped -->
<name>Increment_Counter</name>
<!-- ... -->
</assignments>
<assignments>
<name>Set_Initial_Values</name>
<!-- ... -->
</assignments>
<loops>
<name>Loop_Contacts</name>
<!-- ... -->
</loops>
Why This Happens
When generating flows programmatically or manually editing XML:
- Easy to add a new element near related logic
- Salesforce requires ALL elements of same type to appear consecutively
- The "duplicate" error is misleading - it means elements aren't grouped
Note: API 60.0+ does NOT use <bulkSupport> - bulk processing is automatic.
Common Deployment Errors
| Error | Cause | Solution |
|---|---|---|
| "Element X is duplicated" | Elements not alphabetically ordered | Reorder elements |
| "Element bulkSupport invalid" | Using deprecated element (API 60.0+) | Remove <bulkSupport> |
| "Error parsing file" | Malformed XML | Validate XML syntax |
| "field 'X.Y' doesn't exist" | Relationship field in queriedFields | Use two-step query pattern |
| "$Record__Prior can only be used..." | Using $Record__Prior with Create trigger | Change to Update or CreateAndUpdate |
| "You can't use the Flows action type..." | Subflow in AutoLaunchedFlow | Use inline logic instead |
| "nothing is connected to the Start element" | Empty flow with no elements | Add at least one assignment connected to start |
Start Element Must Have Connector (For Agentforce Flow Actions)
⚠️ DEPLOYMENT BLOCKER: Flows used as Agent Script actions MUST have at least one element connected to the Start element.
What Doesn't Work
<!-- ❌ THIS WILL FAIL DEPLOYMENT -->
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<label>My Agent Flow</label>
<processType>AutoLaunchedFlow</processType>
<status>Active</status>
<variables>
<name>inp_SearchQuery</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<start>
<locationX>50</locationX>
<locationY>50</locationY>
<!-- No connector! -->
</start>
</Flow>
Error: field integrity exception: unknown (The flow can't run because nothing is connected to the Start element.)
Why This Happens
- Minimal flows with only inputs/outputs and no logic still need at least one element
- Salesforce validates that the flow has something to execute
- This is especially common when creating stub/mock flows for testing
Correct Pattern: Add Assignment Element
Even for simple pass-through flows, add at least one assignment:
<Flow xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>66.0</apiVersion>
<label>My Agent Flow</label>
<processType>AutoLaunchedFlow</processType>
<status>Active</status>
<variables>
<name>inp_SearchQuery</name>
<dataType>String</dataType>
<isInput>true</isInput>
<isOutput>false</isOutput>
</variables>
<variables>
<name>out_Result</name>
<dataType>String</dataType>
<isInput>false</isInput>
<isOutput>true</isOutput>
</variables>
<!-- ✅ Start connected to assignment -->
<start>
<locationX>50</locationX>
<locationY>50</locationY>
<connector>
<targetReference>Set_Result</targetReference>
</connector>
</start>
<!-- ✅ At least one element required -->
<assignments>
<name>Set_Result</name>
<label>Set Result</label>
<locationX>176</locationX>
<locationY>158</locationY>
<assignmentItems>
<assignToReference>out_Result</assignToReference>
<operator>Assign</operator>
<value>
<stringValue>Success</stringValue>
</value>
</assignmentItems>
</assignments>
</Flow>
When Creating Agentforce Flow Actions
- Define inputs matching Agent Script action
inputs: - Define outputs matching Agent Script action
outputs: - Add at least one assignment to set output values
- Connect start to assignment via
<connector> - Set status to Active for agent to invoke
Summary: Lessons Learned
Fault Connector Self-Reference
- Problem: Fault connector pointing to the same element
- Error: "The element cannot be connected to itself"
- Solution: Route fault connectors to a dedicated error handler element
XML Element Grouping
- Problem: Elements of same type scattered across the file
- Error: "Element X is duplicated at this location"
- Solution: Group ALL elements of same type together, in alphabetical order by type
Relationship Fields
- Problem: Querying
Parent.Fieldin Get Records - Solution: Two separate queries - child first, then parent by ID
Record-Triggered Flow Architecture
- Problem: Creating loops over triggered records
- Solution: Use
$Recorddirectly - platform handles batching
Deployment
- Problem: Using direct CLI commands
- Solution: Always use sf-deploy skill
$Record Context
- Problem: Confusing Flow's
$Recordwith Process Builder's$Record__c - Solution:
$Recordis single record, use without loops
Standard Objects for Testing
- Problem: Custom objects may not exist in target org
- Solution: When testing flow generation/deployment, prefer standard objects (Account, Contact, Opportunity, Task) for guaranteed deployability
RTF + Subflow Deployment Order (Validated 2026-03-05)
- Problem: Parent RTF references a child subflow that doesn't exist or isn't active
- Info Warning: "The referenced flow X has no active version" (deploys succeed but flow fails at runtime)
- Solution: Deploy and activate child subflow FIRST, then deploy and activate parent RTF
- Activation Order: Child Active -> Parent Active (reverse for deactivation: Parent Draft -> Child Draft)
- Proof: Case Escalation pattern — RTF on Case (after-save, Priority=High AND Status=New) calls Sub_EscalateCase to create Task. Passed positive, negative, and bulk (5x) tests on AgentforceTesting org, API 66.0
More in this playbook
Daily lead steward
Maintain a daily review cockpit for high-intent leads and hand-raisers.
RevOpsMIT Wade Foster + 1Co-founder & CEO @ ZapierFind lead account owner
Resolve the right account owner for a lead using contact, company, and deal ownership evidence.
RevOpsMIT Wade Foster + 1Co-founder & CEO @ ZapierInbound lead audit cx map
Audit inbound lead handling and map the customer experience from source event to follow-up outcome.

