# Automatically email invoices with a trigger

Example of calling a function when the Status value of the Quote object becomes `Accepted`:

```apex
trigger Quote on Quote (after update) {
    
    public List<Quote>      newObjList  {get; set;}
    public Map<Id, Quote>   oldObj      {get; set;}

    newObjList = (List<Quote>)Trigger.new;
    oldObj = (Map<Id, Quote>)Trigger.oldMap;
    if (trigger.isAfter && trigger.isUpdate){   
        for(Quote qu : trigger.new){   
            if (qu.Status == 'Accepted' && qu.Status != oldObj.get(qu.id).Status){
                // Pass the template Id and recordId as parameters
                String templateId = DocumentCustomController.getTemplateId();
                DocumentCustomController.triggeredSavePdf(qu.Id, templateId);
            }
        }        
    }
    
}
```

***

Example function to get a template ID from the template name:

```apex
public static String getTemplateId() {
    String templateId = [SELECT Id 
                            FROM SBLD__DocumentBuilder__c
                            WHERE name = 'BillingStatement' 
                            WITH SECURITY_ENFORCED
                            ORDER BY CreatedDate DESC
                            LIMIT 1][0].Id;
    return templateId;
}

```

***

Example function to send an email to the user:

```apex
public static void sendEmailToUser( List<String> listAttachement) {
    // Add basic details to the email:
    Messaging.SingleEmailMessage clsSingleEmailMessage = new Messaging.SingleEmailMessage();
    clsSingleEmailMessage.setToAddresses(new List<String>{'abc@example.com'});
    clsSingleEmailMessage.setSubject('Email Subject');
    clsSingleEmailMessage.setPlainTextBody('Email Body');
    
    // Add attachment
    ContentVersion clsContentVersion = [SELECT VersionData, PathOnClient FROM ContentVersion WHERE ContentDocumentId = :listAttachement.get(0) WITH SECURITY_ENFORCED][0];
    Messaging.EmailFileAttachment clsEmailFileAttachment = new Messaging.EmailFileAttachment();
    clsEmailFileAttachment.setFileName(clsContentVersion.pathOnClient); 
    clsEmailFileAttachment.setBody(clsContentVersion.versionData);
    clsSingleEmailMessage.setFileAttachments(new Messaging.EmailFileAttachment[] {clsEmailFileAttachment});
    
    // Send the prepared email
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{clsSingleEmailMessage});     
        
}
```

***

Example of saving a Document Template as a PDF

```apex
// Saving Document Template to PDF
@future(callout = true)
public static void triggeredSavePdf(String recordId, String templateId) {

    // Create PDF
    PageReference pdfPage = new PageReference('/apex/SBLD__DocumentBuilderTemplate?recordId=' + templateId + '&targetId=' + recordId);
    Blob pdfContent;

    if(Test.isRunningTest()) { 
        pdfContent = blob.valueOf('Unit.Test'); 
    }else {
        pdfContent = pdfPage.getContentAsPDF();
    }
        
    String title = 'BillingStatement.pdf';

    // Add ContentVersion   
    ContentVersion cv           = new ContentVersion();
    cv.VersionData              = pdfContent;
    cv.Title                    = title;
    cv.PathOnClient             = title;
    cv.OwnerId                  = UserInfo.getUserId();
    cv.ContentLocation          = 'S';

    insert cv;
    
    // Add ContentDocumentLink
    Id conDocId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cv.Id WITH SECURITY_ENFORCED ].ContentDocumentId;
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = conDocId;
    cdl.LinkedEntityId = recordId;
    cdl.ShareType = 'V';
    cdl.Visibility = 'AllUsers';
		
    if (Schema.sObjectType.ContentDocumentLink.fields.ContentDocumentId.isCreateable()) {
            Database.insert(cdl);
    }
    
    // Call the email send method with the attachment added
    listAttachement = new List<String>{conDocId};
    sendEmailToUser(listAttachement);
}
```


---

# 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.smallbuilder.com/smallbuilder-documents/advanced-examples/trigger.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.
