mirror of
https://github.com/github/awesome-copilot.git
synced 2026-04-11 02:35:55 +00:00
Enhance Salesforce Development plugin with new agents and skills (#1326)
* feat: add Salesforce Development plugin bundling Apex, Flow, LWC/Aura, and Visualforce agents
* feat: improve Salesforce plugin agents and add 3 quality skills
- Rewrote all 4 agent files with specific, actionable Salesforce guidance:
- salesforce-apex-triggers: added discovery phase, pattern selection matrix,
PNB test coverage standard, modern Apex idioms (safe nav, null coalescing,
WITH USER_MODE, Assert.*), TAF awareness, anti-patterns table with risks,
and structured output format
- salesforce-aura-lwc: major expansion — PICKLES methodology, data access
pattern selection table, SLDS 2 compliance, WCAG 2.1 AA accessibility
requirements, component communication rules, Jest test requirements, and
output format
- salesforce-flow: major expansion — automation tool confirmation step, flow
type selection matrix, bulk safety rules (no DML/Get Records in loops),
fault connector requirements, Transform element guidance, deployment
safety steps, and output format
- salesforce-visualforce: major expansion — controller pattern selection,
security requirements (CSRF, XSS, FLS/CRUD, SOQL injection), view state
management, performance rules, and output format
- Added 3 new skills to the plugin:
- salesforce-apex-quality: Apex guardrails, governor limit patterns, sharing
model, CRUD/FLS enforcement, injection prevention, PNB testing checklist,
trigger architecture rules, and code examples
- salesforce-flow-design: flow type selection, bulk safety patterns with
correct and incorrect examples, fault path requirements, automation density
checks, screen flow UX guidelines, and deployment safety steps
- salesforce-component-standards: LWC data access patterns, SLDS 2 styling,
accessibility (WCAG 2.1 AA), component communication, Jest requirements,
Aura event design, and Visualforce XSS/CSRF/FLS/view-state standards
- Updated plugin.json v1.0.0 → v1.1.0 with explicit agent paths and skill refs
* fix: resolve codespell error and README drift in Salesforce plugin
- Fix 'ntegrate' codespell false positive in salesforce-aura-lwc agent:
rewrote PICKLES acronym bullets from letter-prefixed (**I**ntegrate)
to full words (**Integrate**) so codespell reads the full word correctly
- Regenerate docs/README.plugins.md to match current build output
(table column padding was updated by the build script)
* fix: regenerate README after rebasing on latest staged
This commit is contained in:
158
skills/salesforce-apex-quality/SKILL.md
Normal file
158
skills/salesforce-apex-quality/SKILL.md
Normal file
@@ -0,0 +1,158 @@
|
||||
---
|
||||
name: salesforce-apex-quality
|
||||
description: 'Apex code quality guardrails for Salesforce development. Enforces bulk-safety rules (no SOQL/DML in loops), sharing model requirements, CRUD/FLS security, SOQL injection prevention, PNB test coverage (Positive / Negative / Bulk), and modern Apex idioms. Use this skill when reviewing or generating Apex classes, trigger handlers, batch jobs, or test classes to catch governor limit risks, security gaps, and quality issues before deployment.'
|
||||
---
|
||||
|
||||
# Salesforce Apex Quality Guardrails
|
||||
|
||||
Apply these checks to every Apex class, trigger, and test file you write or review.
|
||||
|
||||
## Step 1 — Governor Limit Safety Check
|
||||
|
||||
Scan for these patterns before declaring any Apex file acceptable:
|
||||
|
||||
### SOQL and DML in Loops — Automatic Fail
|
||||
|
||||
```apex
|
||||
// ❌ NEVER — causes LimitException at scale
|
||||
for (Account a : accounts) {
|
||||
List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :a.Id]; // SOQL in loop
|
||||
update a; // DML in loop
|
||||
}
|
||||
|
||||
// ✅ ALWAYS — collect, then query/update once
|
||||
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
|
||||
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
|
||||
for (Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]) {
|
||||
if (!contactsByAccount.containsKey(c.AccountId)) {
|
||||
contactsByAccount.put(c.AccountId, new List<Contact>());
|
||||
}
|
||||
contactsByAccount.get(c.AccountId).add(c);
|
||||
}
|
||||
update accounts; // DML once, outside the loop
|
||||
```
|
||||
|
||||
Rule: if you see `[SELECT` or `Database.query`, `insert`, `update`, `delete`, `upsert`, `merge` inside a `for` loop body — stop and refactor before proceeding.
|
||||
|
||||
## Step 2 — Sharing Model Verification
|
||||
|
||||
Every class must declare its sharing intent explicitly. Undeclared sharing inherits from the caller — unpredictable behaviour.
|
||||
|
||||
| Declaration | When to use |
|
||||
|---|---|
|
||||
| `public with sharing class Foo` | Default for all service, handler, selector, and controller classes |
|
||||
| `public without sharing class Foo` | Only when the class must run elevated (e.g. system-level logging, trigger bypass). Requires a code comment explaining why. |
|
||||
| `public inherited sharing class Foo` | Framework entry points that should respect the caller's sharing context |
|
||||
|
||||
If a class does not have one of these three declarations, **add it before writing anything else**.
|
||||
|
||||
## Step 3 — CRUD / FLS Enforcement
|
||||
|
||||
Apex code that reads or writes records on behalf of a user must verify object and field access. The platform does **not** enforce FLS or CRUD automatically in Apex.
|
||||
|
||||
```apex
|
||||
// Check before querying a field
|
||||
if (!Schema.sObjectType.Contact.fields.Email.isAccessible()) {
|
||||
throw new System.NoAccessException();
|
||||
}
|
||||
|
||||
// Or use WITH USER_MODE in SOQL (API 56.0+)
|
||||
List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE AccountId = :accId WITH USER_MODE];
|
||||
|
||||
// Or use Database.query with AccessLevel
|
||||
List<Contact> contacts = Database.query('SELECT Id, Email FROM Contact', AccessLevel.USER_MODE);
|
||||
```
|
||||
|
||||
Rule: any Apex method callable from a UI component, REST endpoint, or `@InvocableMethod` **must** enforce CRUD/FLS. Internal service methods called only from trusted contexts may use `with sharing` instead.
|
||||
|
||||
## Step 4 — SOQL Injection Prevention
|
||||
|
||||
```apex
|
||||
// ❌ NEVER — concatenates user input into SOQL string
|
||||
String soql = 'SELECT Id FROM Account WHERE Name = \'' + userInput + '\'';
|
||||
|
||||
// ✅ ALWAYS — bind variable
|
||||
String soql = [SELECT Id FROM Account WHERE Name = :userInput];
|
||||
|
||||
// ✅ For dynamic SOQL with user-controlled field names — validate against a whitelist
|
||||
Set<String> allowedFields = new Set<String>{'Name', 'Industry', 'AnnualRevenue'};
|
||||
if (!allowedFields.contains(userInput)) {
|
||||
throw new IllegalArgumentException('Field not permitted: ' + userInput);
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5 — Modern Apex Idioms
|
||||
|
||||
Prefer current language features (API 62.0 / Winter '25+):
|
||||
|
||||
| Old pattern | Modern replacement |
|
||||
|---|---|
|
||||
| `if (obj != null) { x = obj.Field__c; }` | `x = obj?.Field__c;` |
|
||||
| `x = (y != null) ? y : defaultVal;` | `x = y ?? defaultVal;` |
|
||||
| `System.assertEquals(expected, actual)` | `Assert.areEqual(expected, actual)` |
|
||||
| `System.assert(condition)` | `Assert.isTrue(condition)` |
|
||||
| `[SELECT ... WHERE ...]` with no sharing context | `[SELECT ... WHERE ... WITH USER_MODE]` |
|
||||
|
||||
## Step 6 — PNB Test Coverage Checklist
|
||||
|
||||
Every feature must be tested across all three paths. Missing any one of these is a quality failure:
|
||||
|
||||
### Positive Path
|
||||
- Expected input → expected output.
|
||||
- Assert the exact field values, record counts, or return values — not just that no exception was thrown.
|
||||
|
||||
### Negative Path
|
||||
- Invalid input, null values, empty collections, and error conditions.
|
||||
- Assert that exceptions are thrown with the correct type and message.
|
||||
- Assert that no records were mutated when the operation should have failed cleanly.
|
||||
|
||||
### Bulk Path
|
||||
- Insert/update/delete **200–251 records** in a single test transaction.
|
||||
- Assert that all records processed correctly — no partial failures from governor limits.
|
||||
- Use `Test.startTest()` / `Test.stopTest()` to isolate governor limit counters for async work.
|
||||
|
||||
### Test Class Rules
|
||||
```apex
|
||||
@isTest(SeeAllData=false) // Required — no exceptions without a documented reason
|
||||
private class AccountServiceTest {
|
||||
|
||||
@TestSetup
|
||||
static void makeData() {
|
||||
// Create all test data here — use a factory if one exists in the project
|
||||
}
|
||||
|
||||
@isTest
|
||||
static void givenValidInput_whenProcessAccounts_thenFieldsUpdated() {
|
||||
// Positive path
|
||||
List<Account> accounts = [SELECT Id FROM Account LIMIT 10];
|
||||
Test.startTest();
|
||||
AccountService.processAccounts(accounts);
|
||||
Test.stopTest();
|
||||
// Assert meaningful outcomes — not just no exception
|
||||
List<Account> updated = [SELECT Status__c FROM Account WHERE Id IN :accounts];
|
||||
Assert.areEqual('Processed', updated[0].Status__c, 'Status should be Processed');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Step 7 — Trigger Architecture Checklist
|
||||
|
||||
- [ ] One trigger per object. If a second trigger exists, consolidate into the handler.
|
||||
- [ ] Trigger body contains only: context checks, handler invocation, and routing logic.
|
||||
- [ ] No business logic, SOQL, or DML directly in the trigger body.
|
||||
- [ ] If a trigger framework (Trigger Actions Framework, ff-apex-common, custom base class) is already in use — extend it. Do not create a parallel pattern.
|
||||
- [ ] Handler class is `with sharing` unless the trigger requires elevated access.
|
||||
|
||||
## Quick Reference — Hardcoded Anti-Patterns Summary
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| SOQL inside `for` loop | Refactor: query before the loop, operate on collections |
|
||||
| DML inside `for` loop | Refactor: collect mutations, DML once after the loop |
|
||||
| Class missing sharing declaration | Add `with sharing` (or document why `without sharing`) |
|
||||
| `escape="false"` on user data (VF) | Remove — auto-escaping enforces XSS prevention |
|
||||
| Empty `catch` block | Add logging and appropriate re-throw or error handling |
|
||||
| String-concatenated SOQL with user input | Replace with bind variable or whitelist validation |
|
||||
| Test with no assertion | Add a meaningful `Assert.*` call |
|
||||
| `System.assert` / `System.assertEquals` style | Upgrade to `Assert.isTrue` / `Assert.areEqual` |
|
||||
| Hardcoded record ID (`'001...'`) | Replace with queried or inserted test record ID |
|
||||
182
skills/salesforce-component-standards/SKILL.md
Normal file
182
skills/salesforce-component-standards/SKILL.md
Normal file
@@ -0,0 +1,182 @@
|
||||
---
|
||||
name: salesforce-component-standards
|
||||
description: 'Quality standards for Salesforce Lightning Web Components (LWC), Aura components, and Visualforce pages. Covers SLDS 2 compliance, accessibility (WCAG 2.1 AA), data access pattern selection, component communication rules, XSS prevention, CSRF enforcement, FLS/CRUD in AuraEnabled methods, view state management, and Jest test requirements. Use this skill when building or reviewing any Salesforce UI component to enforce platform-specific security and quality standards.'
|
||||
---
|
||||
|
||||
# Salesforce Component Quality Standards
|
||||
|
||||
Apply these checks to every LWC, Aura component, and Visualforce page you write or review.
|
||||
|
||||
## Section 1 — LWC Quality Standards
|
||||
|
||||
### 1.1 Data Access Pattern Selection
|
||||
|
||||
Choose the right data access pattern before writing JavaScript controller code:
|
||||
|
||||
| Use case | Pattern | Why |
|
||||
|---|---|---|
|
||||
| Read a single record reactively (follows navigation) | `@wire(getRecord, { recordId, fields })` | Lightning Data Service — cached, reactive |
|
||||
| Standard CRUD form for a single object | `<lightning-record-form>` or `<lightning-record-edit-form>` | Built-in FLS, CRUD, and accessibility |
|
||||
| Complex server query or filtered list | `@wire(apexMethodName, { param })` on a `cacheable=true` method | Allows caching; wire re-fires on param change |
|
||||
| User-triggered action, DML, or non-cacheable server call | Imperative `apexMethodName(params).then(...).catch(...)` | Required for DML — wired methods cannot be `@AuraEnabled` without `cacheable=true` |
|
||||
| Cross-component communication (no shared parent) | Lightning Message Service (LMS) | Decoupled, works across DOM boundaries |
|
||||
| Multi-object graph relationships | GraphQL `@wire(gql, { query, variables })` | Single round-trip for complex related data |
|
||||
|
||||
### 1.2 Security Rules
|
||||
|
||||
| Rule | Enforcement |
|
||||
|---|---|
|
||||
| No raw user data in `innerHTML` | Use `{expression}` binding in the template — the framework auto-escapes. Never use `this.template.querySelector('.el').innerHTML = userValue` |
|
||||
| Apex `@AuraEnabled` methods enforce CRUD/FLS | Use `WITH USER_MODE` in SOQL or explicit `Schema.sObjectType` checks |
|
||||
| No hardcoded org-specific IDs in component JavaScript | Query or pass as a prop — never embed record IDs in source |
|
||||
| `@api` properties from parent: validate before use | A parent can pass anything — validate type and range before using as a query parameter |
|
||||
|
||||
### 1.3 SLDS 2 and Styling Standards
|
||||
|
||||
- **Never** hardcode colours: `color: #FF3366` → use `color: var(--slds-c-button-brand-color-background)` or a semantic SLDS token.
|
||||
- **Never** override SLDS classes with `!important` — compose with custom CSS properties.
|
||||
- Use `<lightning-*>` base components wherever they exist: `lightning-button`, `lightning-input`, `lightning-datatable`, `lightning-card`, etc.
|
||||
- Base components include built-in SLDS 2, dark mode, and accessibility — avoid reimplementing their behaviour.
|
||||
- If using custom CSS, test in both **light mode** and **dark mode** before declaring done.
|
||||
|
||||
### 1.4 Accessibility Requirements (WCAG 2.1 AA)
|
||||
|
||||
Every LWC component must pass all of these before it is considered done:
|
||||
|
||||
- [ ] All form inputs have `<label>` or `aria-label` — never use placeholder as the only label
|
||||
- [ ] All icon-only buttons have `alternative-text` or `aria-label` describing the action
|
||||
- [ ] All interactive elements are reachable and operable by keyboard (Tab, Enter, Space, Escape)
|
||||
- [ ] Colour is not the only means of conveying status — pair with text, icon, or `aria-*` attributes
|
||||
- [ ] Error messages are associated with their input via `aria-describedby`
|
||||
- [ ] Focus management is correct in modals — focus moves into the modal on open and back on close
|
||||
|
||||
### 1.5 Component Communication Rules
|
||||
|
||||
| Direction | Mechanism |
|
||||
|---|---|
|
||||
| Parent → Child | `@api` property or calling a `@api` method |
|
||||
| Child → Parent | `CustomEvent` — `this.dispatchEvent(new CustomEvent('eventname', { detail: data }))` |
|
||||
| Sibling / unrelated components | Lightning Message Service (LMS) |
|
||||
| Never use | `document.querySelector`, `window.*`, or Pub/Sub libraries |
|
||||
|
||||
For Flow screen components:
|
||||
- Events that need to reach the Flow runtime must set `bubbles: true` and `composed: true`.
|
||||
- Expose `@api value` for two-way binding with the Flow variable.
|
||||
|
||||
### 1.6 JavaScript Performance Rules
|
||||
|
||||
- **No side effects in `connectedCallback`**: it runs on every DOM attach — avoid DML, heavy computation, or rendering state mutations here.
|
||||
- **Guard `renderedCallback`**: always use a boolean guard to prevent infinite render loops.
|
||||
- **Avoid reactive property traps**: setting a reactive property inside `renderedCallback` causes a re-render — use it only when necessary and guarded.
|
||||
- **Do not store large datasets in component state** — paginate or stream large results instead.
|
||||
|
||||
### 1.7 Jest Test Requirements
|
||||
|
||||
Every component that handles user interaction or retrieves Apex data must have a Jest test:
|
||||
|
||||
```javascript
|
||||
// Minimum test coverage expectations
|
||||
it('renders the component with correct title', async () => { ... });
|
||||
it('calls apex method and displays results', async () => { ... }); // Wire mock
|
||||
it('dispatches event when button is clicked', async () => { ... });
|
||||
it('shows error state when apex call fails', async () => { ... }); // Error path
|
||||
```
|
||||
|
||||
Use `@salesforce/sfdx-lwc-jest` mocking utilities:
|
||||
- `wire` adapter mocking: `setImmediate` + `emit({ data, error })`
|
||||
- Apex method mocking: `jest.mock('@salesforce/apex/MyClass.myMethod', ...)`
|
||||
|
||||
---
|
||||
|
||||
## Section 2 — Aura Component Standards
|
||||
|
||||
### 2.1 When to Use Aura vs LWC
|
||||
|
||||
- **New components: always LWC** unless the target context is Aura-only (e.g. extending `force:appPage`, using Aura-specific events in a legacy managed package).
|
||||
- **Migrating Aura to LWC**: prefer LWC, migrate component-by-component; LWC can be embedded inside Aura components.
|
||||
|
||||
### 2.2 Aura Security Rules
|
||||
|
||||
- `@AuraEnabled` controller methods must declare `with sharing` and enforce CRUD/FLS — Aura does **not** enforce them automatically.
|
||||
- Never use `{!v.something}` with unescaped user data in `<div>` unbound helpers — use `<ui:outputText value="{!v.text}" />` or `<c:something>` to escape.
|
||||
- Validate all inputs from component attributes before using them in SOQL / Apex logic.
|
||||
|
||||
### 2.3 Aura Event Design
|
||||
|
||||
- **Component events** for parent-child communication — lowest scope.
|
||||
- **Application events** only when component events cannot reach the target — they broadcast to the entire app and can be a performance and maintenance problem.
|
||||
- For hybrid LWC + Aura stacks: use Lightning Message Service to decouple communication — do not rely on Aura application events reaching LWC components.
|
||||
|
||||
---
|
||||
|
||||
## Section 3 — Visualforce Security Standards
|
||||
|
||||
### 3.1 XSS Prevention
|
||||
|
||||
```xml
|
||||
<!-- ❌ NEVER — renders raw user input as HTML -->
|
||||
<apex:outputText value="{!userInput}" escape="false" />
|
||||
|
||||
<!-- ✅ ALWAYS — auto-escaping on -->
|
||||
<apex:outputText value="{!userInput}" />
|
||||
<!-- Default escape="true" — platform HTML-encodes the output -->
|
||||
```
|
||||
|
||||
Rule: `escape="false"` is never acceptable for user-controlled data. If rich text must be rendered, sanitise server-side with a whitelist before output.
|
||||
|
||||
### 3.2 CSRF Protection
|
||||
|
||||
Use `<apex:form>` for all postback actions — the platform injects a CSRF token automatically into the form. Do **not** use raw `<form method="POST">` HTML elements, which bypass CSRF protection.
|
||||
|
||||
### 3.3 SOQL Injection Prevention in Controllers
|
||||
|
||||
```apex
|
||||
// ❌ NEVER
|
||||
String soql = 'SELECT Id FROM Account WHERE Name = \'' + ApexPages.currentPage().getParameters().get('name') + '\'';
|
||||
List<Account> results = Database.query(soql);
|
||||
|
||||
// ✅ ALWAYS — bind variable
|
||||
String nameParam = ApexPages.currentPage().getParameters().get('name');
|
||||
List<Account> results = [SELECT Id FROM Account WHERE Name = :nameParam];
|
||||
```
|
||||
|
||||
### 3.4 View State Management Checklist
|
||||
|
||||
- [ ] View state is under 135 KB (check in browser developer tools or the Salesforce View State tab)
|
||||
- [ ] Fields used only for server-side calculations are declared `transient`
|
||||
- [ ] Large collections are not persisted across postbacks unnecessarily
|
||||
- [ ] `readonly="true"` is set on `<apex:page>` for read-only pages to skip view-state serialisation
|
||||
|
||||
### 3.5 FLS / CRUD in Visualforce Controllers
|
||||
|
||||
```apex
|
||||
// Before reading a field
|
||||
if (!Schema.sObjectType.Account.fields.Revenue__c.isAccessible()) {
|
||||
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'You do not have access to this field.'));
|
||||
return null;
|
||||
}
|
||||
|
||||
// Before performing DML
|
||||
if (!Schema.sObjectType.Account.isDeletable()) {
|
||||
throw new System.NoAccessException();
|
||||
}
|
||||
```
|
||||
|
||||
Standard controllers enforce FLS for bound fields automatically. **Custom controllers do not** — FLS must be enforced manually.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference — Component Anti-Patterns Summary
|
||||
|
||||
| Anti-pattern | Technology | Risk | Fix |
|
||||
|---|---|---|---|
|
||||
| `innerHTML` with user data | LWC | XSS | Use template bindings `{expression}` |
|
||||
| Hardcoded hex colours | LWC/Aura | Dark-mode / SLDS 2 break | Use SLDS CSS custom properties |
|
||||
| Missing `aria-label` on icon buttons | LWC/Aura/VF | Accessibility failure | Add `alternative-text` or `aria-label` |
|
||||
| No guard in `renderedCallback` | LWC | Infinite rerender loop | Add `hasRendered` boolean guard |
|
||||
| Application event for parent-child | Aura | Unnecessary broadcast scope | Use component event instead |
|
||||
| `escape="false"` on user data | Visualforce | XSS | Remove — use default escaping |
|
||||
| Raw `<form>` postback | Visualforce | CSRF vulnerability | Use `<apex:form>` |
|
||||
| No `with sharing` on custom controller | VF / Apex | Data exposure | Add `with sharing` declaration |
|
||||
| FLS not checked in custom controller | VF / Apex | Privilege escalation | Add `Schema.sObjectType` checks |
|
||||
| SOQL concatenated with URL param | VF / Apex | SOQL injection | Use bind variables |
|
||||
135
skills/salesforce-flow-design/SKILL.md
Normal file
135
skills/salesforce-flow-design/SKILL.md
Normal file
@@ -0,0 +1,135 @@
|
||||
---
|
||||
name: salesforce-flow-design
|
||||
description: 'Salesforce Flow architecture decisions, flow type selection, bulk safety validation, and fault handling standards. Use this skill when designing or reviewing Record-Triggered, Screen, Autolaunched, Scheduled, or Platform Event flows to ensure correct type selection, no DML/Get Records in loops, proper fault connectors on all data-changing elements, and appropriate automation density checks before deployment.'
|
||||
---
|
||||
|
||||
# Salesforce Flow Design and Validation
|
||||
|
||||
Apply these checks to every Flow you design, build, or review.
|
||||
|
||||
## Step 1 — Confirm Flow Is the Right Tool
|
||||
|
||||
Before designing a Flow, verify that a lighter-weight declarative option cannot solve the problem:
|
||||
|
||||
| Requirement | Best tool |
|
||||
|---|---|
|
||||
| Calculate a field value with no side effects | Formula field |
|
||||
| Prevent a bad record save with a user message | Validation rule |
|
||||
| Sum or count child records on a parent | Roll-up Summary field |
|
||||
| Complex multi-object logic, callouts, or high volume | Apex (Queueable / Batch) — not Flow |
|
||||
| Everything else | Flow ✓ |
|
||||
|
||||
If you are building a Flow that could be replaced by a formula field or validation rule, ask the user to confirm the requirement is genuinely more complex.
|
||||
|
||||
## Step 2 — Select the Correct Flow Type
|
||||
|
||||
| Use case | Flow type | Key constraint |
|
||||
|---|---|---|
|
||||
| Update a field on the same record before it is saved | Before-save Record-Triggered | Cannot send emails, make callouts, or change related records |
|
||||
| Create/update related records, emails, callouts | After-save Record-Triggered | Runs after commit — avoid recursion traps |
|
||||
| Guide a user through a multi-step UI process | Screen Flow | Cannot be triggered by a record event automatically |
|
||||
| Reusable background logic called from another Flow | Autolaunched (Subflow) | Input/output variables define the contract |
|
||||
| Logic invoked from Apex `@InvocableMethod` | Autolaunched (Invocable) | Must declare input/output variables |
|
||||
| Time-based batch processing | Scheduled Flow | Runs in batch context — respect governor limits |
|
||||
| Respond to events (Platform Events / CDC) | Platform Event–Triggered | Runs asynchronously — eventual consistency |
|
||||
|
||||
**Decision rule**: choose before-save when you only need to change the triggering record's own fields. Move to after-save the moment you need to touch related records, send emails, or make callouts.
|
||||
|
||||
## Step 3 — Bulk Safety Checklist
|
||||
|
||||
These patterns are governor limit failures at scale. Check for all of them before the Flow is activated.
|
||||
|
||||
### DML in Loops — Automatic Fail
|
||||
|
||||
```
|
||||
Loop element
|
||||
└── Create Records / Update Records / Delete Records ← ❌ DML inside loop
|
||||
```
|
||||
|
||||
Fix: collect records inside the loop into a collection variable, then run the DML element **outside** the loop.
|
||||
|
||||
### Get Records in Loops — Automatic Fail
|
||||
|
||||
```
|
||||
Loop element
|
||||
└── Get Records ← ❌ SOQL inside loop
|
||||
```
|
||||
|
||||
Fix: perform the Get Records query **before** the loop, then loop over the collection variable.
|
||||
|
||||
### Correct Bulk Pattern
|
||||
|
||||
```
|
||||
Get Records — collect all records in one query
|
||||
└── Loop over the collection variable
|
||||
└── Decision / Assignment (no DML, no Get Records)
|
||||
└── After the loop: Create/Update/Delete Records — one DML operation
|
||||
```
|
||||
|
||||
### Transform vs Loop
|
||||
When the goal is reshaping a collection (e.g. mapping field values from one object to another), use the **Transform** element instead of a Loop + Assignment pattern. Transform is bulk-safe by design and produces cleaner Flow graphs.
|
||||
|
||||
## Step 4 — Fault Path Requirements
|
||||
|
||||
Every element that can fail at runtime must have a fault connector. Flows without fault paths surface raw system errors to users.
|
||||
|
||||
### Elements That Require Fault Connectors
|
||||
- Create Records
|
||||
- Update Records
|
||||
- Delete Records
|
||||
- Get Records (when accessing a required record that might not exist)
|
||||
- Send Email
|
||||
- HTTP Callout / External Service action
|
||||
- Apex action (invocable)
|
||||
- Subflow (if the subflow can throw a fault)
|
||||
|
||||
### Fault Handler Pattern
|
||||
```
|
||||
Fault connector → Log Error (Create Records on a logging object or fire a Platform Event)
|
||||
→ Screen element with user-friendly message (Screen Flows)
|
||||
→ Stop / End element (Record-Triggered Flows)
|
||||
```
|
||||
|
||||
Never connect a fault path back to the same element that faulted — this creates an infinite loop.
|
||||
|
||||
## Step 5 — Automation Density Check
|
||||
|
||||
Before deploying, verify there are no overlapping automations on the same object and trigger event:
|
||||
|
||||
- Other active Record-Triggered Flows on the same `Object` + `When to Run` combination
|
||||
- Legacy Process Builder rules still active on the same object
|
||||
- Workflow Rules that fire on the same field changes
|
||||
- Apex triggers that also run on the same `before insert` / `after update` context
|
||||
|
||||
Overlapping automations can cause unexpected ordering, recursion, and governor limit failures. Document the automation inventory for the object before activating.
|
||||
|
||||
## Step 6 — Screen Flow UX Guidelines
|
||||
|
||||
- Every path through a Screen Flow must reach an **End** element — no orphan branches.
|
||||
- Provide a **Back** navigation option on multi-step flows unless back-navigation would corrupt data.
|
||||
- Use `lightning-input` and SLDS-compliant components for all user inputs — do not use HTML form elements.
|
||||
- Validate required inputs on the screen before the user can advance — use Flow validation rules on the screen.
|
||||
- Handle the **Pause** element if the flow may need to await user action across sessions.
|
||||
|
||||
## Step 7 — Deployment Safety
|
||||
|
||||
```
|
||||
Deploy as Draft → Test with 1 record → Test with 200+ records → Activate
|
||||
```
|
||||
|
||||
- Always deploy as **Draft** first and test thoroughly before activation.
|
||||
- For Record-Triggered Flows: test with the exact entry conditions (e.g. `ISCHANGED(Status)` — ensure the test data actually triggers the condition).
|
||||
- For Scheduled Flows: test with a small batch in a sandbox before enabling in production.
|
||||
- Check the Automation Density score for the object — more than 3 active automations on a single object increases order-of-execution risk.
|
||||
|
||||
## Quick Reference — Flow Anti-Patterns Summary
|
||||
|
||||
| Anti-pattern | Risk | Fix |
|
||||
|---|---|---|
|
||||
| DML element inside a Loop | Governor limit exception | Move DML outside the loop |
|
||||
| Get Records inside a Loop | SOQL governor limit exception | Query before the loop |
|
||||
| No fault connector on DML/email/callout element | Unhandled exception surfaced to user | Add fault path to every such element |
|
||||
| Updating the triggering record in an after-save flow with no recursion guard | Infinite trigger loops | Add an entry condition or recursion guard variable |
|
||||
| Looping directly on `$Record` collection | Incorrect behaviour at scale | Assign to a collection variable first, then loop |
|
||||
| Process Builder still active alongside a new Flow | Double-execution, unexpected ordering | Deactivate Process Builder before activating the Flow |
|
||||
| Screen Flow with no End element on all branches | Runtime error or stuck user | Ensure every branch resolves to an End element |
|
||||
Reference in New Issue
Block a user