Skip to content

Instantly share code, notes, and snippets.

@Todd-HPRelate
Created June 24, 2014 21:03
Show Gist options
  • Save Todd-HPRelate/705e14732309e31edbf1 to your computer and use it in GitHub Desktop.
Save Todd-HPRelate/705e14732309e31edbf1 to your computer and use it in GitHub Desktop.
Example Visual Force Page and Apex code to create a button in Salesforce that will automate the PDF creation using the 'Account' standard object in HP Relate.
<!------------------------------------------------------------------------------------
Create_Relate_PDF
Example Visual Force Page to create a button in Salesforce that will automate the PDF creation using the 'Account' standard object
(c) Copyright 2014 HEWLETT-PACKARD COMPANY
DISCLAIMER: The sample code described herein is provided on an "as is" basis, without warrant of any
kind, to the fullest extent permitted by law. Both Hewlett-Packard Company and I do not warrant or
guarantee the individual success developers may have in implementing the sample code on their
development platforms.
Hewlett-Packard Company and I do not warrant, guarantee or make any representations regarding the
use, results of use, accuracy, timeliness or completeness of any data or information relating to the
sample code. Hewlett-Packard Company and I disclaim all warranties, express or implied, and in
particular, disclaim all warranties of merchantability, fitness for a particular purpose, and
warranties related to the code, or any service or software related thereto.
Hewlett-Packard Company and I shall not be liable for any direct, indirect or consequential damages
or costs of any type arising out of any action taken by you or others related to the sample code.
-------------------------------------------------------------------------------------->
<apex:page standardController="Account" extensions="CreatePDFControllerExtension">
<apex:form >
<apex:pageBlock title="Create a Document" rendered="{!!isTemplateSelected}" >
<apex:pageBlockSection columns="1" >
Document Name:
<apex:inputText id="inputDocName" value="{!documentName}" style="width:200px" />
</apex:pageBlockSection>
<br />
Select a Template to create the document.
<apex:pageBlockTable value="{!templates}" var="template">
<!-- <apex:column value="{!template.Id}" /> -->
<apex:column title="Name">
<apex:commandLink >
<apex:outputText value="{!template.Name}" />
<apex:param name="selectedTemplate" value="{!template.Id}" assignTo="{!selectedTemplate}" />
</apex:commandLink>
</apex:column>
<apex:column value="{!template.relate__description__c}" />
</apex:pageBlockTable>
</apex:pageBlock>
<apex:outputPanel Id="processingPanel">
<apex:pageMessages />
<apex:actionPoller interval="5" action="{!ProcessRequest}" enabled="{!IsProcessing}" rerender="processingPanel" />
<apex:outputPanel rendered="{!IsProcessing}">
<apex:image url="/img/loading32.gif"/>
Creating PDF...
<br />
<br />
<br />
The PDF will be added to the Chatter feed for the object. <br />
The PDF is also accessible via Notes &amp; Attachments.
<br />
</apex:outputPanel>
<apex:iframe src="{!pdfLocation}" scrolling="true" id="pdfFrame" height="1100" width="850" rendered="{!showFrame}"></apex:iframe>
</apex:outputPanel>
</apex:form>
</apex:page>
<!------------------------------------------------------------------------------------
CreatePDFControllerExtension.cls
Example Apex code to create a button in Salesforce that will automate the PDF creation using the 'Account' standard bject
(c) Copyright 2014 HEWLETT-PACKARD COMPANY
DISCLAIMER: The sample code described herein is provided on an "as is" basis, without warrant of any
kind, to the fullest extent permitted by law. Both Hewlett-Packard Company and I do not warrant or
guarantee the individual success developers may have in implementing the sample code on their
development platforms.
Hewlett-Packard Company and I do not warrant, guarantee or make any representations regarding the
use, results of use, accuracy, timeliness or completeness of any data or information relating to the
sample code. Hewlett-Packard Company and I disclaim all warranties, express or implied, and in
particular, disclaim all warranties of merchantability, fitness for a particular purpose, and
warranties related to the code, or any service or software related thereto.
Hewlett-Packard Company and I shall not be liable for any direct, indirect or consequential damages
or costs of any type arising out of any action taken by you or others related to the sample code.
-------------------------------------------------------------------------------------->
public class CreatePDFControllerExtension
{
// The currently selected account
private Account account;
// Store the template selected by the user
public Id selectedTemplate {get; set; }
// Variable to track the fulfillment (pdf creation) request
public Relate__Relate_Fulfillment__c fulfillment {get;set;}
// Variable to track the Relate document
public Id relateDocId {get; set;}
// Variable to track the fulfillment (pdf creation) request ID
public Id pdfDocId {get; set;}
// Variable to hold the name to use for the Relate Doc and PDF.
public String documentName {get; set;}
// Returns true if template has been selected and we are in
// the process of generating a document/pdf.
public Boolean IsProcessing
{
get
{
return (selectedTemplate != NULL) && IsProcessing;
}
set;
}
public Boolean showFrame {get; set;}
public String pdfLocation {get; set;}
// Custom constructor to extend the Account controller
public CreatePDFControllerExtension( ApexPages.StandardController controller )
{
// Get the current Account from the controller.
account = (Account)controller.getRecord();
if (account == null)
{
ApexPages.Message errMessage = new ApexPages.Message(
ApexPages.Severity.FATAL,
'Error initializing CreatePDFController.');
ApexPages.addMessage(errMessage);
}
// Provide a default name.
documentName = 'Volume Commitment FY' + String.valueOf(getCurrentFY());
// Default to processing.
IsProcessing = true;
// Default to no iFrame
showFrame = false;
}
// Returns TRUE if a Template has been selected,
// FALSE if it is un-initialized
public Boolean getIsTemplateSelected()
{
return selectedTemplate != NULL;
}
// Returns all Templates ordered by Name
public List<relate__Relate_Template__c> getTemplates()
{
return
[SELECT Id, Name, relate__description__c FROM relate__Relate_Template__c ORDER BY Name];
}
// Creates a Relate document, then a PDF and stores it in the Chatter feed.
public PageReference ProcessRequest()
{
try
{
// Get the document name entered on the screen if there is one.
// This allows the user to override the name.
String docName = ApexPages.currentPage().getParameters().get('inputDocName');
if ( (docName != null) && (docName.length() > 0) )
{
documentName = docName;
}
// When showFrame is set to true, we are done.
// We set IsProcessing to false and return.
if (showFrame)
{
IsProcessing = false;
return null;
}
// RelateDocId is null when the Relate Document record has yet to be created.
if (relateDocId == null)
{
createDoc();
}
else
{
// If the Relate document record has been created, we need to check it's state
// Once it is in the 'Created' state, we can create the PDF.
if (pdfDocId == null)
{
Relate__Relate_Document__c doc =
[SELECT Relate__State__c, Relate__Error_Message__c
FROM Relate__Relate_Document__c WHERE Id = :RelateDocId];
if(doc.Relate__State__c == 'Created')
{
pdfDocId = Relate.RelateAPI.CreateDocumentPDFAsObjectAttachment(
RelateDocId, documentName + '.pdf', account.Id);
}
// If an error occurred on the server side, HP Relate will report an error in the
// relate__Relate_Error_Message__c field and set the state to Error.
else if (doc.Relate__State__c == 'Error')
{
ApexPages.Message myMsg = new ApexPages.Message(
ApexPages.Severity.FATAL,
'Error creating Relate Document : '
+ doc.Relate__Error_Message__c);
ApexPages.addMessage(myMsg);
IsProcessing = false;
}
}
else
{
fulfillment = [SELECT Relate__state__c, Relate__runId__c, Relate__action__c, id,
Relate__requestId__c, Relate__docUrl__c, Relate__message__c,
Relate__Content_Name__c, Relate__relateId__c, Relate__outputDocId__c
FROM Relate__Relate_Fulfillment__c
WHERE Id = :pdfDocId];
// When finished, setting showFrame and pdflocation
// will setup the iFrame so that it is visible.
if(fulfillment.Relate__State__c == 'Finished')
{
this.showFrame = true;
this.pdfLocation = fulfillment.Relate__docURL__c;
this.IsProcessing = false;
return null;
}
else if (fulfillment.Relate__State__c == 'Error')
{
ApexPages.Message myMsg;
ApexPages.Severity severity;
// Iterate through all messages, add to page messages.
List<relate__Relate_Fulfillment_Message__c> messages =
[SELECT relate__Message__c, relate__Message_Type__c, Id,
relate__Relate_Fulfillment__c, Name
FROM relate__Relate_Fulfillment_Message__c
WHERE relate__Relate_Fulfillment__c = :fulfillment.id];
if (messages.size() == 0)
{
myMsg = new ApexPages.Message(
ApexPages.Severity.FATAL,
'An error occurred creating your document. Please try again.');
ApexPages.addMessage(myMsg);
}
else
{
for(relate__Relate_Fulfillment_Message__c msg : messages)
{
if (msg.relate__Message_Type__c == 'Error') {
severity = ApexPages.Severity.ERROR;
} else {
if (msg.relate__Message_Type__c == 'Warning') {
severity = ApexPages.Severity.WARNING;
} else {
severity = ApexPages.Severity.INFO;
}
}
myMsg = new ApexPages.Message(severity, msg.relate__Message__c);
ApexPages.addMessage(myMsg);
}
}
// Stop processing to display errors
IsProcessing = false;
}
}
}
}
catch (Exception ex)
{
ApexPages.Message myMsg = new ApexPages.Message(
ApexPages.Severity.FATAL,
'Error processing Request : ' + ex.getMessage());
ApexPages.addMessage(myMsg);
IsProcessing = false;
}
return null;
}
// Creates a Relate Document using the API call
private void createDoc()
{
Map<String, Id> mappedData = new Map<String, ID>();
try
{
// Add the account ID. Use the API Name of the lookup field as the key to the map.
mappedData.put('Account__c', account.Id);
// Create a Relate Doc with the selected template, name and account.
// The Relate doc will treat the Account as its parent.
relateDocId = Relate.RelateAPI.CreateRelateDocument( selectedTemplate, documentName, mappedData, account.Id );
}
catch (Exception e)
{
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Error creating Relate document : ' + e.getMessage());
ApexPages.addMessage(myMsg);
IsProcessing = false;
}
}
// Use the FiscalYear information from the Organization
// to determine the Fiscal Year from today's date.
private integer getCurrentFY() {
Organization orgInfo = [SELECT FiscalYearStartMonth, UsesStartDateAsFiscalYearName
FROM Organization
WHERE id=:Userinfo.getOrganizationId()];
Date today = system.today();
Integer currentFY;
if (today.month() >= orgInfo.FiscalYearStartMonth) {
if (orgInfo.UsesStartDateAsFiscalYearName) {
currentFY = today.year();
} else {
currentFY = today.year() + 1;
}
} else {
if (orgInfo.UsesStartDateAsFiscalYearName) {
currentFY = today.year() - 1;
} else {
currentFY = today.year();
}
}
return currentFY;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment