Skip to navigation

How to send an envelope from an Apex trigger

View as Markdown

This topic demonstrates how to send an envelope using an Apex trigger.

Prerequisites

  1. Install the Docusign eSignature for Salesforce managed package.
  2. Create a subdomain for your Salesforce organization by enabling “My Domain.”
  3. Select the Docusign Setup tab and complete the login step.
  4. Configure the Contact object within your Salesforce organization with the custom fields necessary to run the code below. In the Object Manager menu, find Contact then navigate to Fields & Relationships where you can select New to add a custom field. Add a new field of type Picklist with the label Docusign_Status. The picklist needs to have values Email Docusign.

Required data

Running the code in this how-to requires this data:

Data elementDescription
{TEMPLATE_ID}A GUID value that identifies a Docusign template that is used to create a Docusign envelope. This value is automatically generated by Docusign when the template is created.

Step 1. Define your class with an inner class

The accompanying code demonstrates how to define an inner class creating the EnvelopeSendResponse object that will be returned by methods defined later in this how-to. The object contains a message string and a boolean status to indicate whether the envelope was sent successfully. The class definition shown here should be used to replace the class stub shown in the class declaration from Step 1.

Apex
public with sharing class SendEnvelopeFromTriggerController {
public class EnvelopeSendResponse {
public String message {get; private set;}
public Boolean status {get; private set;}
public EnvelopeSendResponse(final String message, final Boolean status){
this.message = message;
this.status = status;
}
}
}

Step 2. Write a method to send the envelope

Define a method that will send the envelope when the actions defined in the trigger have been completed. First, use a Salesforce Object Query Language (SOQL) query to get the contact’s information using their source ID. Create a new envelope using the dfsle.EnvelopeService.getEmptyEnvelope method. Add the customer’s information to a new dfsle.Recipient object and add that recipient to the envelope.

Next, create a new document and add it to the envelope. In this example, you create a document representing a Docusign template using the dfsle.Document.fromTemplate method and passing in the ID of a valid Docusign template. Then, use the envelope’s dfsle.Envelope.withDocuments method to add the document to the envelope. Finally, send the envelope using the dfsle.EnvelopeService.sendEnvelope method.

Apex
public static EnvelopeSendResponse sendEnvelope(final Id mySourceId) {
EnvelopeSendResponse response;
try {
// Capture customer details
Contact myCustomer = [SELECT Id, Name, Email FROM Contact WHERE Id =:mySourceId];
// Create an empty envelope
dfsle.Envelope myEnvelope = dfsle.EnvelopeService.getEmptyEnvelope
(new dfsle.Entity(mySourceId));
// Setup recipient data
dfsle.Recipient myRecipient = dfsle.Recipient.fromSource
(myCustomer.Name, myCustomer.Email, null, 'Signer 1', new dfsle.Entity(mySourceId));
// Add Recipient to the Envelope
myEnvelope = myEnvelope.withRecipients(new List<dfsle.Recipient> { myRecipient });
// myTemplateId contains the DocuSign Id of the DocuSign Template
dfsle.UUID myTemplateId = dfsle.UUID.parse('bf7ca600-XXXX-XXXX-XXXX-06e7f3b9e8ce');
// Create a new document for the Envelope
dfsle.Document myDocument = dfsle.Document.fromTemplate(
myTemplateId, // templateId in dfsle.UUID format
'myTemplate'); // The name of the template
// Add document to the Envelope
myEnvelope = myEnvelope.withDocuments(new List<dfsle.Document> { myDocument });
// Send the envelope
myEnvelope = dfsle.EnvelopeService.sendEnvelope(
myEnvelope, // The envelope to send
true); // Send now?
response = new EnvelopeSendResponse('Envelope sent successfully', true);
}
catch(Exception ex) {
response = new EnvelopeSendResponse(ex.getMessage(), false);
}
return response;
}

Step 3. Create a trigger handler class

The accompanying code defines the class and method that will be called within the trigger. This method will execute the method defined in the previous step, calling the Docusign API to send an envelope. The trigger cannot call the method defined in Step 3 directly because Apex requires that methods with Web Service Callouts are executed asynchronously from triggers. The @future annotation is added to this method to ensure that the call to the Docusign eSignature API is made asynchronously.

Apex
public class DocuSignStatusTriggerHandler{
@future (callout=true)
// Handler for Order complete
public static void handleOrderComplete(final Id contactId) {
// Call the SendEnvelopeFromTriggerController class sendEnvelope method to invoke the DocuSign API's for sending envelope
SendEnvelopeFromTriggerController.sendEnvelope(contactId);
}
}

Step 4. Create a trigger

Finally, create the trigger that will determine the conditions under which the envelope will be sent. This trigger listens for updates on Contact objects and executes the DocuSignStatusTriggerHandler class when a Contact’s custom field, Docusign_Status, is set to the value Email Docusign. Notice that the Docusign_Status field becomes DocuSign_Status__c in the code. All custom fields are given the __c suffix in the code to differentiate them from default objects and fields. Create a new trigger in the Developer Console by opening the File menu and selecting New, then Apex Trigger. Replace the code that says before insert with after insert, after update, after delete as shown in the accompanying code. This will allow your trigger to take action after the Contact object has been updated.

Note: Unlike the code in other examples, the code in this how-to won’t be executed through the Developer Console in Salesforce. It will be executed when the conditions defined by the trigger are met. To run this code, edit a Contact object in Salesforce and set its Docusign_Status field to Email Docusign.

View the source code for this how-to on GitHub: Apex.

Apex
trigger Trigger_ContactAfterUpdate on Contact (after insert, after update, after delete) {
if (trigger.isUpdate)
{
for(contact aC : trigger.new)
{
if (aC.DocuSign_Status__c=='Email DocuSign') // Test Field called on the contact. This is not a DocuSignStatus Object
{
DocuSignStatusTriggerHandler.handleOrderComplete(aC.Id);
}
}
}
}

Next steps