Salesforce Documents

Trigger Document Generation From Salesforce Flow: A Clean API Pattern

Renato Mateus · Founder, RMMS.Cloud
·10 min read
  • Salesforce Flow
  • automation API
  • Apex
  • no-code
  • DocForge

The wrong shape: per-template Apex classes

It is common to see a separate Apex class per template: GenerateProposalPDF, GenerateInvoicePDF, GenerateNDA. Each one duplicates logic and drifts. Admins cannot wire any of them into a Flow without dev help.

The right shape is one stable, well-documented Flow-callable action plus an Apex API that takes template ID and source record ID as inputs. Everything else is configuration.

The action interface that Flow loves

  • Input: templateId, sourceRecordId, options map (locale, currency override, attach mode).
  • Output: documentId, contentVersionId, fileUrl, status, errorMessage.
  • Bulk-friendly: accepts a list and returns a list, so screen-flow and record-triggered flows both work.
  • Idempotent: same template + record + run key returns the same document; safe to retry.

Patterns Flow admins use

  1. Quick action on Opportunity: screen flow with template picker → invoke action → show success.
  2. Record-triggered: when stage = "Closed Won," generate the welcome packet.
  3. Scheduled flow: monthly statement generation for active accounts.
  4. Sub-flow in larger automation: contract → e-sign → onboarding email all chained.

Where Apex API stays in the picture

  • Apex triggers and asynchronous jobs needing precise control.
  • Integration code in managed packages.
  • Complex batch jobs that need governor-limit-aware patterns.
  • External-system callbacks (webhook receivers) that fan back into Salesforce.

Authentication, permissions, and named credentials

The action must run under the user's permissions (CRUD/FLS on source records) and respect sharing rules. Named credentials handle the external generator endpoint—no hardcoded secrets. Permission sets gate who can invoke the action; specific templates can have stricter permission scoping.

Error handling that admins can debug

  • Structured error codes (TEMPLATE_NOT_FOUND, FIELD_MAPPING_INVALID, SOURCE_RECORD_MISSING_FIELD) with human messages.
  • Optional fault path in Flow with the error message to display to the user.
  • Generator audit log written to a custom object regardless of success/fail.
  • Retry semantics documented: which errors are transient (retry) vs permanent (escalate).

Testing the Flow path

  1. Unit tests for the invocable action with mocked generator endpoint.
  2. Flow tests with sample data sets covering success and failure paths.
  3. Sandbox integration test against the real generator.
  4. Performance test with bulk inputs (200 records in one invocation).

The reusability benefit, with numbers

Before: 12 templates × 8 hours of dev per template change = 96 dev hours per quarter spent on layout tweaks. After: one stable API + admins editing visual templates → dev hours drop to near zero for layout changes; dev focuses on real business logic.

Calling document generation from Flow without governor-limit roulette

Flow excels at orchestration; PDF engines excel at render. Keep heavy work in an invocable action or external API that returns a file ID—not inline Apex string building in a loop over 200 line items.

Design inputs as a structured JSON payload built from Flow formulas so the same action works from record-triggered Flow, screen Flow, and REST.

Invocable action contract

InputTypeRequired
recordIdIdYes
templateApiNameStringYes
localeStringNo (org default)
attachToRecordBooleanYes
idempotencyKeyStringRecommended

Output handling in Flow

  1. Branch on success boolean—never assume attach worked because no fault.
  2. Store contentDocumentId and fileHash in variables for downstream steps.
  3. On failure, route to fault path with errorCode for rep-facing message.
  4. Async path for batches over 50 lines—call @future or queueable from invocable.
  5. Log each invocation to custom object Document_Generation_Log__c for support.

Example: screen Flow for ad-hoc NDA

Rep launches screen Flow on Opportunity, picks NDA template and signatory contact. Invocable generates PDF in 4 seconds, returns contentDocumentId; Flow shows success toast with link. Same action is reused in record-triggered Flow when Stage = Negotiation—one API surface, two entry points, identical audit log schema.

Bulk and scheduled generation patterns

Record-triggered Flows work for one Opportunity; scheduled Flows batch-closing invoices need queueable handoff when row count exceeds 50. Pass batch ID through idempotency key so partial failures resume without duplicate files.

Surface batch status on a custom dashboard: total, success, failed, retry—finance should not open Debug Log to learn a nightly job stalled.

Version your invocable action API when adding required inputs—Flows fail at runtime without compile-time errors if a new required field deploys before Flow updates.

Expose generation status on the Opportunity layout as a read-only component—reps stop pinging admins when they see In Progress vs Failed with error code.

Document maximum line-item count per invocation in admin guide—Flow timeouts on 400-line Opportunities need batch mode, not repeated clicks.

Pin invocable action versions in Flow metadata so sandbox refreshes do not silently point at deprecated API signatures.

Document automation earns trust when ops owns the pipeline: weekly batch reviews, mapping change control, and a single owner who can explain every failed row to finance without opening three tools. Treat the generator like payroll—silent success, loud failures, zero mystery duplicates in numbering or filenames.

Where DocForge for Salesforce fits

DocForge for Salesforce ships a Flow-callable invocable action with the interface above, a documented Apex API, structured errors, idempotency, and bulk support. Sign in and wire your first record-triggered flow in a sandbox.