Automation: Triggering the SDK via Platform Events
Why?
The S-Docs SDK is a synchronous engine that often performs heavy processing. To protect Salesforce database integrity, the SDK cannot be invoked directly within an Apex Trigger. Attempting to do so will throw a SDOC.Exceptions.GenerationException.
To automate document generation based on a record update or insert, you must decouple the transaction. Platform Events are the most robust way to "hand off" the generation task to a fresh transaction with its own set of governor limits.
What: The Event-Driven Architecture
Instead of the Trigger doing the work, it simply "announces" that work needs to be done by publishing a Platform Event. A subscriber (a Flow or another Trigger) then picks up that announcement and executes the SDK in a separate context.
Solve: Implementation Steps
1. Define the Platform Event
Navigate to Setup > Platform Events and create a new event (e.g., Document_Request__e).
Publish Behavior: Publish After Commit (Recommended to ensure the base record is saved before generation starts).
Custom Fields:
Record_ID__c(Text, 18)Template_ID__c(Text, 18)
2. Publish from the Trigger
In your Apex Trigger, instantiate and publish the event. This is a "low-cost" operation that is allowed within the trigger context.
Java
trigger OpportunityTrigger on Opportunity (after update) {
List<Document_Request__e> docEvents = new List<Document_Request__e>();
for (Opportunity opp : Trigger.new) {
// Only trigger if the Stage changes to 'Closed Won'
if (opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed Won') {
docEvents.add(new Document_Request__e(
Record_ID__c = opp.Id,
Template_ID__c = '00Xxxxxxxxxxxxx' // Your Template ID
));
}
}
if (!docEvents.isEmpty()) {
EventBus.publish(docEvents);
}
}3. Subscribe via Flow (The "Listener")
Create a new Platform Event-Triggered Flow.
Object: Select your
Document_Request__e.Action: Add the S-Docs: Generate Document Invocable Action.
Configuration: *
Record ID:{$Record.Record_ID__c}Template Name or ID:{$Record.Template_ID__c}
Technical Benefits
Governor Limit Reset: The Flow runs in a new transaction, giving the SDK a full 101 SOQL query limit and a fresh heap size.
Asynchronous UX: The user's "Save" action isn't slowed down by the document generation; the file appears on the record a few seconds later.
Error Isolation: If the document generation fails, it will not roll back the original record update that fired the trigger.
⚠️ Constraints
Eventual Consistency: There is a slight delay (typically 1–3 seconds) between the record save and the document appearing.
No Direct UI Feedback: Because this happens in the background, you cannot "toast" a success message to the user's screen directly from the Flow.
Loop Protection: Ensure your Trigger logic is specific (e.g., checking
oldMap) to prevent an infinite loop of events.
Last updated
Was this helpful?

