# 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.sdocs.com/developer-hub/document-generation-workflows/apex-and-programmatic-automation/software-development-kit/implementation-solves/automation-triggering-the-sdk-via-platform-events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
