Tag Archives: Salesforce.com

Automated PDF Generation in Salesforce Using Conga Composer

Posted on

A practical Salesforce architecture for generating PDFs with Conga Composer using Flow, asynchronous Apex, and REST-based integration.

Introduction

Salesforce is excellent at managing customer data and automating business processes. But when teams need to generate complex documents such as sales contracts, renewal notices, and customer agreements, the native platform often needs help from a dedicated document generation tool.

In enterprise Salesforce implementations, document generation is rarely a one-click problem. Sales and renewal processes often require:

  • Dynamic data from multiple Salesforce objects
  • Conditional logic based on deal type, product, customer segment, or region
  • Corporate-approved branding and formatting
  • Automated generation as part of a larger business workflow

This article walks through a practical architecture for automated PDF generation in Salesforce using Conga Composer. The focus is not only the Conga merge itself, but the surrounding automation pattern: Flow, asynchronous Apex, REST-based invocation, and downstream document reuse.

The key design choice is to treat Conga Composer as part of the Salesforce automation architecture, rather than as a standalone button users click manually. Done well, automated document generation reduces manual errors, supports compliance, and gives sales and operations teams a reliable document pipeline.

Business Scenario

Consider a sales process where a PDF must be generated immediately after an Opportunity is closed won and the related Order is created. The generated document may need to support email delivery, physical mailing, audit history, or later customer service workflows.

The main requirements are:

  • Generate the PDF automatically after a business transaction completes.
  • Use Salesforce data as the source of truth.
  • Save the generated PDF so other processes can reuse it.
  • Make the document visible from the Order, Opportunity, and Account.
  • Keep the design scalable enough for enterprise sales and renewal processes.

In the example architecture, the Order becomes the document anchor. After an Opportunity is marked Closed Won, Salesforce creates an Order with the data required for the merge. Conga Composer generates the PDF, saves it to the Order, and asynchronous Apex associates the same file with the Opportunity and Account for visibility and downstream use.

Solution Overview

The solution combines three main components:

  • Salesforce Flow to start the process when the Order is ready.
  • Asynchronous Apex to handle callouts, polling, persistence, and follow-up work.
  • Conga Composer REST APIs to generate and save the PDF document.

At a high level, the workflow is:

  1. An Opportunity is marked Closed Won.
  2. A Salesforce Order is created with the relevant data.
  3. A record-triggered Flow starts an asynchronous Apex process.
  4. Apex selects the correct Conga template based on the Order and related records.
  5. Apex invokes Conga Composer through the REST API.
  6. Conga generates the PDF and saves it to Salesforce.
  7. Apex associates the PDF with the Order, Opportunity, and Account.
  8. Downstream processes use the document for email, mailing, compliance, or fulfillment.

Salesforce Automation Design

Use the Order as the Document Anchor

Using the Salesforce Order as the primary document anchor keeps the document generation process stable. The Opportunity may continue to evolve as part of sales reporting, but the Order is usually a better representation of the completed transaction that needs documentation.

In this pattern, the Order serves as:

  • The primary source of data for PDF generation
  • The first attachment target for the generated PDF
  • A stable anchor for downstream automation

Keep Flow Simple and Move Heavy Work to Apex

A record-triggered Flow can detect that the Order is ready and then hand off the heavy work to asynchronous Apex, such as a Queueable class. This keeps the Flow maintainable while giving Apex responsibility for external callouts, polling, error handling, and file association.

This approach also avoids putting long-running integration logic directly inside the transaction that creates or updates the Order.

The benefits are practical:

  • Governor limits are easier to manage.
  • The user interface remains responsive.
  • Callouts to Conga Composer can be handled in a controlled async process.
  • The architecture can support retries, logging, and operational monitoring.

Conga Composer Integration

REST-Based Invocation Pattern

For automated enterprise workflows, REST-based invocation is usually the cleaner pattern. Apex authenticates with Conga, starts the merge request, receives a correlation ID, and then checks the generation status until the document is complete.

The integration typically includes:

  • OAuth authentication with Conga using a client ID and client secret.
  • A POST request to the Conga Ingress API to initiate document generation.
  • A correlation ID returned by Conga for tracking the async generation request.
  • A status check that confirms when the PDF has been generated.
  • Persistence of the generated PDF back into Salesforce based on the request options.

The request normally includes the Salesforce access token, Salesforce instance URL, Conga template ID, and Salesforce master object ID, such as the Order ID.

Apex Code Example: Conga REST Ingress Call

The following simplified Apex example shows how an asynchronous Salesforce process can initiate PDF generation for an Order. In production, use secure credential storage, add retry and timeout handling, and log integration events so support teams can troubleshoot failed document jobs.

// 1. Set the Conga Ingress API endpoint
String endpoint = 'https://coreapps-rlsprod.congacloud.com/api/ingress/v1/Merge';
// 2. Build the JSON request body
Map<String, Object> legacyOptions = new Map<String, Object>{
'TemplateId' => 'a4LXXXXXXXXXXXXXXX', // Conga template record ID
'APIMode' => '1', // Attach document to master object
'DefaultPDF' => '1' // Generate PDF output
};
Map<String, Object> jsonBody = new Map<String, Object>{
'access_token' => sfAccessToken,
'instance_url' => Url.getOrgDomainUrl().toExternalForm(),
'salesforceMasterObjId' => orderId,
'LegacyOptions' => legacyOptions
};
// 3. Prepare the HTTP request
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', 'Bearer ' + congaAuthToken);
req.setBody(JSON.serialize(jsonBody));
req.setTimeout(60000);
// 4. Send the request
Http http = new Http();
HttpResponse res = http.send(req);
// 5. Handle the response
if (res.getStatusCode() == 200 || res.getStatusCode() == 201) {
Map<String, Object> responseMap =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) responseMap.get('correlationId');
}
throw new CalloutException('Conga API Error: ' + res.getBody());

URL-Based Invocation as a Legacy Pattern

Conga Composer also supports a URL-based invocation model. Some Salesforce implementations still use it, especially older automations or button-driven processes. In that model, an HTTPS GET request passes parameters through a generated URL, and authentication is commonly handled through the Salesforce session context.

That pattern can still work, but REST-based invocation is better suited for scalable automated document generation because it separates initiation, status tracking, and persistence more cleanly.

Template Selection Logic

Conga Composer templates are Salesforce records, which makes them manageable from inside the platform. A template is stored as anAPXTCong4__Conga_Template__crecord and can be selected dynamically using SOQL, Flow configuration, custom metadata, or business rules implemented in Apex.

This gives the implementation useful flexibility:

  • Different templates can be selected based on Order, Account, Opportunity, product, region, or customer segment.
  • Template changes can be made without redeploying Apex code.
  • Template access can follow Salesforce security and governance practices.
  • Business teams can evolve document content while the integration pattern remains stable.

Document Persistence Strategy

Once Conga finishes processing, the generated PDF should be saved in a place where users and automation can reliably find it. The first save target is usually the master object passed to Conga, such as the Order. From there, asynchronous Apex can associate the same document with related records.

A common persistence strategy is:

  • Attach or relate the generated PDF to the Order.
  • Associate the same PDF with the Opportunity for sales visibility.
  • Associate the same PDF with the Account for account-level history.
  • Trigger downstream processes only after the PDF is confirmed to exist.

Decoupling document generation from distribution makes the architecture more flexible. Email delivery, mailing integrations, compliance workflows, and customer service processes can all consume the same generated document without each one needing to understand the Conga merge process.

Conclusion

Automated document generation is a core capability in many Salesforce sales and renewal processes. Salesforce provides the data, workflow, and platform automation foundation, while Conga Composer provides the document merge and formatting engine needed for polished customer-facing PDFs.

The strongest implementations treat document generation as an architecture pattern, not a one-off button. Flow starts the process, asynchronous Apex handles integration and orchestration, Conga generates the PDF, and Salesforce stores the resulting document where users and downstream automation can use it.

For teams building scalable Salesforce processes, this pattern reduces manual work, improves document consistency, and creates a reliable foundation for email, mailing, fulfillment, and audit workflows.

Programmatically Check the salesforce field properties

It is very common that we need to check the field properties of a salesforce object. If there are a large number of fields, it is very time consuming to click on each field one at a time from salesforce user interface.  The following Apex code demonstrates how to print the nullable properties of all the fields in the Account object. You can change it to other objects or print different field properties.

Schema.DescribeSObjectResult r = Account.sObjectType.getDescribe();

Map<String,Schema.SObjectField> M = r.fields.getMap();
for(String fieldName : M.keySet()){
Schema.SObjectField field = M.get(fieldName);
Schema.DescribeFieldResult F = field.getDescribe();
Boolean isFieldreq  = F.isNillable() ;
System.debug (fieldName + ‘ is null:  ‘ +  isFieldreq);

}

Salesforce rule and trigger execution order

Posted on

The following is the order salesforce logic is applied to a record.

  1. Old record loaded from database (or initialized for new inserts)
  2. New record values overwrite old values
  3. System Validation Rules
  4. All Apex before triggers (EE / UE only)
  5. Custom Validation Rules
  6. Record saved to database (but not committed)
  7. Record reloaded from database
  8. All Apex after triggers (EE / UE only)
  9. Assignment rules
  10. Auto-response rules
  11. Workflow rules
  12. Escalation rules
  13. Parent Rollup Summary Formula value updated (if present)
  14. Database commit
  15. Post-commit logic (sending email)

Additional notes:

There is no way to control the order of execution within each group above.

Workflow field updates that run based on an approval process or time-dependent action do not trigger any rules.

Formula fields do not execute in this way. They calculate and display their results real-time whenever the field is accessed in any way. So for example if a Workflow Rule uses a Formula Field in its criteria or formula, the formula field is evaluated when the Workflow Rule criteria is checked.

The features that have to be enabled by Salesforce Support

Posted on

Hide SFDC Brand
Hide SFDC Logo in CSS (Hide Salesforce Logo in Self Service Portal)
Manage Person Accounts
Multi-currency
More Decimals on Price
Single Sign-On
Translation Workbench
Daily Lead Limit
Daily Case Limit
Upload Size (MB)
Max Active Rules Per Entity (mass workflow rules)
Max Sharing Rules Per Entity
Max Actions per rule
Customizable Forecasting
Create Audit Fields (System Modifiable Fields)
Extended Mail Merge
Encrypted Fields
Disable Email Change Notification AND/OR Add Allowed Domain
Trial Expiration Date
Mass Email Permission (for trial)
Massmail Recipient Limit
Roll-Up Summary Field
Enable Content Delivery Setup
API Returns the state [address] regardless of the user locale
Advanced Search in Sidebar
Campaign association to opportunity from contact
Case duration age in business hours
HTML Solutions
Local Names
Quantity schedule revenue related
Rename Standard Objects
End User Languages
Supply Default Opportunity line item values
Territory Management
License Count Synchronization Between Sandbox & Production
Change “System Administrator” user e-mail address
Data Export
Divisions Enabled
Daily Massmail Limit
Increase API Request Limit Override
Daily Incoming Email Limit
One-Off Salesforce Sandbox Refresh
[Please be advised that the only time we are able to approve sandbox refreshes is when the sandbox did not refresh correctly due to a bug or error.]
Migrating Archived Activities