Difference between revisions of "Document Templates"

From AgileApps Support Wiki
imported>Aeric
Tag: Manual revert
Β 
(77 intermediate revisions by 3 users not shown)
Line 1: Line 1:
'''Designer > Presentation > Print Templates'''
'''[[File:GearIcon.png]] > Customization > Objects > {object} > Document Templates''' Β 


Print templates let you generate PDF documents for selected records.
Document templates (aka Print Templates) are used to generate a document from selected records, [[Lookup]] target records, and even related records.


==About Print Templates==
==About Document Templates==
Print templates are powerful tools, allowing you to set up documents that pull information from a specific object and merge into an HTML or JSP page. Print templates are loaded into the platform and can be used to set up standard proposals, queries, contracts, invoices, etc., and generate PDF documents unique to specific records - any document that you can dream up.
Using Document Templates, you merge record data into a pre-formed template, to create a formatted document. You can use such templates to create prefilled forms, invoices, contracts, and other types of documents using data stored in your application.


===Examples===
Document Templates can be based on an HTML file, a Word document, a PowerPoint presentation, or a JSP [[Page]] stored in the platform. You can use them to print individual records, or to print multiple records displayed in a [[View]].
:*Create an Expense Report to be used in expense management application
:*Print an Employee Benefit Form


{{Note|The files used for HTML, Word, and PowerPoint based Print templates are first created outside of the platform. The initial version of a JSP [[Page]]-based template is created inside the platform. Once created, print templates can be downloaded, edited, and uploaded again.}}
{{Note| HTML, Word, and PowerPoint files are created outside of the platform, and then uploaded for use. Once created, they can be downloaded, edited, and uploaded again. JSP [[Page]]s are created and edited either in the platform, or using the [[Eclipse Plug-in]].}}


:''Learn more:'' [[Sample Print Templates]] you can customize and use.
===Document Template Formats===
Document Templates can be created in a variety of formats including:
:* [[Create an MS Word Document Template| MS Word Document]]
:* [[Create a PowerPoint Document Template|PowerPoint Presentation]]
:* [[Create an HTML Document Template|HTML page]]
:* [[Create a JSP Page Document Template|JSP Page]]
:* [[Create a Compound Document Template|Compound Template]] - a composite of multiple parts


===How Print Templates Work===
===How Document Templates Work===


The Print Templates feature lets you generate graphical mail-merge-style PDF documents using variables and rich formatting. You can use these templates to create prefilled forms, invoices, contracts, and other types of documents using data stored in your application. The platform uses the Apache Velocity templating engine to create powerful dynamic documents. Β 
At bottom, Document templates are formatted documents with ''variables'' you create by inserting specific codes. When you generate a PDF, the codes are replaced by record data, images, and charts, to create a customized version of the template.


:''Learn more:'' http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html
For even more dynamic documents, the platform uses the Apache Velocity templating engine, which allows you to vary the content of the document based on record data, and to create repeating parts for related records, like the OrderItems in an Order.
:''Learn more:'' http://velocity.apache.org/engine/releases/velocity-{{VelocityVersion}}/user-guide.html


In outline, the process looks like this:
In outline, the process for creating a Document Template looks like this:
# You create a document (on your local file system) or an HTML/JSP [[Page]] in the platform that includes all of the fixed text and images you want to include in your template. <br>''Learn more:'' [[HTML Resources]]
# You create a document (on your local file system) or an JSP [[Page]] in the platform that includes all of the fixed text and images you want to include in your template.
#:
# While creating the document, you make note of the platform data you want to add:
# While creating the document, you make note of the platform data you want to add:
#* Record fields
#* Record fields
Line 29: Line 35:
#* Company fields Β 
#* Company fields Β 
#* Fields from [[#Accessing Related Records|Related Records]]
#* Fields from [[#Accessing Related Records|Related Records]]
#:
# You use the [[Template Variable Tool]] to get the field names you need to customize the HTML file with fields and images taken from data records. Β 
# You use the [[Template Variable Tool]] to get the field names you need to customize the HTML file with fields and images taken from data records. Β 
#:
# You use the [[Reports]] tool to get the identifiers for charts you want to add.
# You use the [[Reports]] tool to get the identifiers for charts you want to add.
#:
# You use the Velocity scripting language to build logic into the template, changing the content based on data parameters.
# You use the Velocity scripting language to build logic into the template, changing the content based on data parameters.


Line 36: Line 45:
:* CSS styles can be embedded into HTML files. External CSS files can also be referenced in the template, if they are first uploaded as [[Static Resources]].
:* CSS styles can be embedded into HTML files. External CSS files can also be referenced in the template, if they are first uploaded as [[Static Resources]].
:* Fixed images can be inserted into Word and PowerPoint files directly.
:* Fixed images can be inserted into Word and PowerPoint files directly.
:* Fixed images in an HTML file need to be stored on the platform either as [[Static Resources]], or as [[Public Document]]s.
:* Fixed images in an HTML file need to be stored somewhere on the web, and accessed using URLs.
{{Note|A Static Resource is available only to a logged-in user. A Public Document is visible to anyone who has the link. From the standpoint of a Print Template, the difference is immaterial, since a user has to be logged in to print a record.}}


==Working with Print Templates==
===Use a Template to Generate a Document===
When viewing a record:
#In the '''Actions''' list, click '''Print'''.
#Select the [[Form]] or [[Document Template]] to use for printing.
#Choose whether to print in Portrait or Landscape mode.
#Choose whether to save the resulting document or view it in a new window online.
#Click '''[Print]'''.
{{Note|<br>In essence, a [[Form]] is just another kind of template--only it's one that you create with the interactive Form editor. So Forms also appear in the list of Document Templates.}}
<!--
===Use a Template to Print a List of Records===
'''''This functionality may not be supported for all objects.'''''
# View a list of objects
# Do a search or add criteria to modify the view
# Select the records to print.<br>(Click ''All'' to select all displayed records.)
# Select '''More Actions > Print'''
# Use the current view, choose a new one, or select records manually.
# For '''Print Layout''', choose '''Use a Document Template'''
# Select the template to use
# Set the page orientation
# Click '''[Print]'''
-->


===Add a Print Template===
==Working with Document Templates==
{{:Add a Print Template}}


===Edit a Print Template based on a Platform JSP/HTML Page===
===Add a Document Template===
# Click '''Designer > Logic > Pages > {page}'''
{{:Add a Document Template}}
===Edit a Document Template based on a Platform JSP/HTML Page===
# Click '''[[File:GearIcon.png]] > Customization > Developer Resources > Pages > {page}'''
# Edit the page.
# Edit the page.
#: ''Learn more:'' [[Pages]]
#: ''Learn more:'' [[Pages]]
#If you need the names of additional variables:
#If you need the names of additional variables:
#: a. Click '''Designer > Data > Objects > {object} > Print Templates'''
#: a. Click '''[[File:GearIcon.png]] > Customization > Objects > {object} > Document Templates'''
#: b. View the template to access the Template Variable Tool:
#: b. View the template to access the Template Variable Tool:
#:[[File:TemplateVariableTool.jpg]]
#:[[File:TemplateVariableTool.jpg]]


===Edit a File-Based Print Template===
===Edit a File-Based Document Template===
#Click '''Designer > Data > Objects > {object} > Print Templates'''
#Click the ''Download'' link on the template you want to copy to your local system.
#Click the ''Download'' link on the template you want to copy to your local system.
#Make changes to the template.
#Make changes to the template.
Line 64: Line 92:
{{Warn|Be sure to click the right link. The existing template page will be replaced by the new one.}}
{{Warn|Be sure to click the right link. The existing template page will be replaced by the new one.}}


===Use a Template to Print a Record===
===Add an Image===
#Open an object record.
{{:Common:Adding Images to Templates}}
#Click the '''[Print]''' button.
#Select ''Template based'' to create an HTML page using the Print Template.
#Select the Template
#Optionally, Select PDF format to get the results in PDF format. (Default is HTML.)
#Click '''[Print]'''.<br>A new window opens to display the results.
#Copy content from the resulting HTML page, print it, or save the page to your local system.
Β 
===Use a Template to Print a List of Records===
# Visit '''Workspace > {object}'''
# Select a view
# Do a search or add criteria to modify the view
# Select the records to print.<br>(Click ''All'' to select all displayed records.)
# Select '''More Actions > Print'''
# Use the current view, choose a new one, or select records manually.
# For '''Print Layout''', choose '''Use a Print Template'''
# Select the template to use
# Set the page orientation
# Click '''[Print]'''
Β 
===Insert Images, Charts, and Template Variables===
See the instructions for the kind of template you are creating:
:* [[Create a JSP Page Print Template]]
:* [[Create an HTML Print Template]]
:* [[Create an MS Word Print Template]]
:* [[Create a PowerPoint Print Template]]
Β 
==Accessing Related Records==
In a {{type|}}, fields from ''related records'' can be added to a Print Template. (That is, records in a Object that has a [[Lookup]] to the current object.)
Β 
For example, OrderItems has a lookup to Orders, so in a Print Template for Orders, related OrderItems records can be accessed. (In an object [[Form]], related records are typically displayed in a [[Subform]], although they need not be.)
Β 
When formatting a record in the current object for printing, those related records and the fields they contain can be processed in a loop.
Β 
===Finding and Using Related Record Variables===
Β 
====Finding Related-Record Variables====
Related Object variables can be found in the [[Template Variable Tool]]. Here, the related OrderItems objects are being chosen from the category list:
Β 
:[[File:TemplateVariableToolRelatedObjects.png]]
Β 
Here, the Tag Name field is being selected from the Many to Many relationship with the Tags object:
Β 
:[[File:TemplateVariableToolRelatedManyToManyObject.png]]
Β 
The object that is directly connected to Orders is Orders_Tags -- a [[Junction Object]] that has Lookups to both Orders and Tags. In that object, the Lookup to Tags is called ''Related to Tags''. Within that group, the Tag Name field is listed, along with other fields in the Tags object.
Β 
Once selected, the variable name will appear in the Variable area:
:<tt>$Orders_Tags_record.related_to_Tags.tag_name</tt>
Β 
where:
:* <tt>$Orders_Tags_record</tt> is the expected loop variable for the $Orders_Tags [[Junction Object]] records
:* <tt>related_to__Tags</tt> is the name of the Lookup field in the Junction Object that references a Tags record
:* <tt>tag_name</tt> is the field we want to display
:* The "dot" separator (<tt>.</tt>) joins each of the segments in the variable name
Β 
====Processing Related Records a Loop====
Typically, you'll create a table for the related records, define its headings, and then create a row for a single record, putting the related-record variables into the cells of the row. You then enclose that row in a loop, using the <tt>#foreach</tt> instruction defined by the Velocity templating engine.
Β 
Related records are returned in an array, so the loop creates a new table row for each record in the array.
Β 
For example (with formatting attributes removed for simplicity):
:<syntaxhighlight lang="xml" enclose="div">
<table>
<tbody>
<tr>
Β  Β  <th>Quantity</th>
Β  Β  <th>Product </th>Β  Β  Β  Β  Β  Β  Β 
Β  Β  <th>Unit Price</th>
Β  Β  <th>Amount</th>
</tr>
</tbody>
Β 
#foreach( $OrderItems_record in $OrderItems )
<tr>Β  Β  Β  Β 
Β  Β  <td>$OrderItems_record.item_quantity</td>
Β  Β  <td>$OrderItems_record.related_to_ProductInventory.product_name</td>
Β  Β  <td>$OrderItems_record.item_price</td>
Β  Β  <td>$OrderItems_record.total</td>
</tr>
#end
Β 
...
</table>
</syntaxhighlight>
Β 
where:
:* The <tt><nowiki><tbody></nowiki></tt> element is required around the header row.
Β 
:* The Velocity <tt>#foreach</tt> directive does the looping.
:: ''Learn more:'' http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html
:* The looping construct defines <tt>$OrderItems_record</tt> as a loop variable.
:* The loop variable iterates over the <tt>$OrderItems</tt> array.
:* The <tt>$OrderItems</tt> array is automatically available in the template, because OrderItems is a [[Related Object]]. (All related objects are available. Each is an array.)
Β 
====Special Considerations for Subform Variables====
Totals and additional computation fields defined for a [[Subform]] are also available in the [[Template Variable Tool]]. To find them, you access the main object (not the object displayed in the Subform), because those fields are added to the object that ''contains'' the Subform.
Β 
For example, the Subform for OrderItems totals the $Amount column, and then does additional computations on it to add a surcharge. Those values are shown in the <tt>$Orders Fields</tt> category as <tt>Total $Amount</tt> and <tt>Shipping for $Amount</tt>, respectively. (The final total is shown as <tt>Net Total $Amount</tt>.)
Β 
===Sample Print Template for an Order Invoice===
This sample:
:* Creates an invoice for an order, showing all items in it
:* Gets the name and price of order items from the ProductInventory object
:* Uses Velocity <tt>#foreach</tt> processing to process OrderItems records for an Order
:* Uses Velocity <tt>#if</tt> conditionals to display surcharge and discount rows only if those values are present
Β 
:<syntaxhighlight lang="xml" enclose="div">
<html><head>
<title></title>
<style>
div {Β 
Β  Β  Β  padding-top: 5px;Β 
Β  Β  Β  padding-bottom: 5px;Β 
Β  Β  Β  padding-right: 5px;Β 
Β  Β  Β  padding-left: 30px;Β 
Β  Β  Β  border: 3px;Β 
Β  margin-top: 5%;
Β  margin-right: 40%;
Β  margin-bottom: 5%;
Β  margin-left: 5%;
Β  Β  }
</style>
Β 
</head><body bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
Β 
<div style="width:100%">
Β 
<imgΒ  width="100" height="100"Β  src="http://justanothermobilemonday.com/Wordpress/wp-content/uploads/2009/10/android-robot-logo2.jpg" alt="Company logo" />&nbsp;&nbsp;&nbsp; <---- Company Logo Here<br/>
<font size="5"><b>$company.name</b></font><b><br />
<br/>
$company.street&nbsp;&nbsp;<br>
$company.city, $company.state, <br>
$company.country - $company.zip
&nbsp;<br>
&nbsp;(Phone): $user.phone
<hr width="100%" size="1" />
<br />
Β 
<h2 align="center">Order<b> Invoice</b></h2>
<p></p>
<p align="center"><b>Invoice Date:</b> $Orders.date_created </p>
Β 
<br/><br/>
<b><u>Bill To: </u></b><br />
<font size="2">$Orders.account.name - $Orders.account.number</font></b>
<br />$Orders.account.street<br />
$Orders.account.city,&nbsp;$Orders.account.state, <br>
$Orders.account.country - $Orders.account.zip<br />
Β 
(Phone): $Orders.account.phone <br />
<br />
<br />
<b>Invoice #: $Orders.order_number <br />
</b>&nbsp;
</p>
Β 
<table border="1" cellpadding="5" cellspacing="0" width="600">
Β 
<!-- HEADER -->
<tbody>
<tr>
Β  Β  <th>Quantity</th>
Β  Β  <th>Product </th>Β  Β  Β  Β  Β  Β  Β 
Β  Β  <th>Unit Price</th>
Β  Β  <th>Amount</th>
</tr>
</tbody>
Β 
#foreach( $OrderItems_record in $OrderItems )
<tr>
<td width="350">$OrderItems_record.item_quantity</td>
<td width="100" align="CENTER">$OrderItems_record.related_to_ProductInventory.product_name</td>
<td width="100" align="CENTER"> $OrderItems_record.item_price</td>
<td width="100" align="CENTER"> $OrderItems_record.totalΒ  Β  </td>
</tr>
#end
Β 
<tr>
<td colspan="2">&nbsp;</td>
<td style="border: solid 1px #000000;" align="Right">Sub Total</td>
<td style="border: solid 1px #000000;" align="center">$Order.grid_comptn_f5631e34b39f4ba39a98559c7215a3b4</td>
</tr>
Β 
#if( $Orders.grid_surcharge_031f67dd4b3946949df2da276e5c82a6 > 0 )
<tr>
<td colspan="2">&nbsp;</td>
<td style="border: solid 1px #000000;" align="Right">Surcharge</td>
<td style="border: solid 1px #000000;" align="center">$Orders.grid_surcharge_f5631e34b39f4ba39a98559c7215a3b4</td>
</tr>
#end
Β 
#if( $Orders.grid_discount_031f67dd4b3946949df2da276e5c82a6 > 0 )
<tr>
<td colspan="2">&nbsp;</td>
<td style="border: solid 1px #000000;" align="Right">Discount</td>
<td style="border: solid 1px #000000;" align="center">$Orders.grid_discount_f5631e34b39f4ba39a98559c7215a3b4</td>
</tr>
#end
Β 
<tr>
<td colspan="2">&nbsp;</td>
<td style="border: solid 1px #000000;" align="Right">Tax</td>
<td style="border: solid 1px #000000;" align="center">$Orders.grid_tax_f5631e34b39f4ba39a98559c7215a3b4</td>
</tr>
Β 
<tr>
<td colspan="2">&nbsp;</td>
<td style="border: solid 1px #000000;" align="Right">Shipping</td>
<td style="border: solid 1px #000000;" align="center">$Orders.grid_shipping_f5631e34b39f4ba39a98559c7215a3b4</td>
</tr>
Β 
<tr>
<td colspan="2">&nbsp;</td>
<td style="border: solid 1px #000000;" align="Right"><b>TOTAL AMOUNT DUE</b></td>
<td style="border: solid 1px #000000;" align="center"><b>$Orders.grid_net_total_f5631e34b39f4ba39a98559c7215a3b4</b></td>
</tr>Β  Β 
</table>
Β 
<br /><br />
Payment Due upon reciept<br />
Thank you for your business!
</div>
Β  Β  Β 
<p></p>
</body>
</html>
</syntaxhighlight>
Β 
The Subform part of the resulting invoice then looks something like this:


:[[File:OrderInvoiceSampleSegment.png]]
==Customizing Data Sent to the Template with a Document Template Class==
{{:Document Template Classes}}


(The [{{DOCHOST}}/files/OrderInvoiceTemplate.html Order Invoice template] and the [{{DOCHOST}}/files/OrderInvoiceSample.html Order Invoice sample] file are both available in the downloads area.)
==Troubleshooting Tips==
:* When testing the value of a boolean field, it's important to know that the value is a case-sensitive string that is either <tt>"Yes"</tt> or <tt>"No"</tt>.
:* Velocity syntax errors cause the Velocity process to die.
:* Not all browsers display an error message when such errors occur. (Firefox does.)
:* If you're seeing what appears to be a "silent failure', try switching browsers.
:* When the error occurs in a Word or PowerPoint template, it can be difficult to pinpoint the cause of the error.
:* Converting the template to HTML helps to pinpoint the line that has the problem.
:* When a Word or PowerPoint template fails, a process instance is left running, with a corrupted document that can't be read. Subsequent attempts to open the document report an error message, and an additional process is left running.
:* On a PC, the processes can be found and killed from the Task Manager.
:* Each open process makes a temporary copy of the template, with a name like, "Template.docx (1)".
:* The existence of those undeletable template copies is a sign that processes have been left running.
:* When the processes are killed, the template copies disappear.
:* The RTA field type is not supported in document templates of type .docx/.ppt. If you use RTA field type, then when you print the document template, Rich Text Area field is printed with HTML tags.
:* When you have an error message "Word found unreadable content in <fileName>" while accessing the document, check the uploaded document template '''Access Permission'''. The file uploaded in Document Templates should be in Unrestricted mode.To check if the document is in Unrestricted Access: Click on '''File''' -'''Info''' - '''Protect Document''' - '''Restrict Access''' - '''Unrestricted Access'''.Β 
::[[File:Unrestricted access.png]]
<noinclude>
<noinclude>


[[Category:Presentation | 5]]
[[Category:Object Aspects]]
[[Category:Objects| 9.1]]
[[Category:Design]]
[[Category:{{features}}]]
[[Category:Glossary]]
[[Category:Tutorials]]
</noinclude>
</noinclude>

Latest revision as of 10:46, 28 July 2023

GearIcon.png > Customization > Objects > {object} > Document Templates

Document templates (aka Print Templates) are used to generate a document from selected records, Lookup target records, and even related records.

About Document Templates

Using Document Templates, you merge record data into a pre-formed template, to create a formatted document. You can use such templates to create prefilled forms, invoices, contracts, and other types of documents using data stored in your application.

Document Templates can be based on an HTML file, a Word document, a PowerPoint presentation, or a JSP Page stored in the platform. You can use them to print individual records, or to print multiple records displayed in a View.

Notepad.png

Note: HTML, Word, and PowerPoint files are created outside of the platform, and then uploaded for use. Once created, they can be downloaded, edited, and uploaded again. JSP Pages are created and edited either in the platform, or using the Eclipse Plug-in.

Document Template Formats

Document Templates can be created in a variety of formats including:

How Document Templates Work

At bottom, Document templates are formatted documents with variables you create by inserting specific codes. When you generate a PDF, the codes are replaced by record data, images, and charts, to create a customized version of the template.

For even more dynamic documents, the platform uses the Apache Velocity templating engine, which allows you to vary the content of the document based on record data, and to create repeating parts for related records, like the OrderItems in an Order.

Learn more: http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html

In outline, the process for creating a Document Template looks like this:

  1. You create a document (on your local file system) or an JSP Page in the platform that includes all of the fixed text and images you want to include in your template.
  2. While creating the document, you make note of the platform data you want to add:
    • Record fields
    • Record images
    • Charts created from Reports
    • User fields
    • Company fields
    • Fields from Related Records
  3. You use the Template Variable Tool to get the field names you need to customize the HTML file with fields and images taken from data records.
  4. You use the Reports tool to get the identifiers for charts you want to add.
  5. You use the Velocity scripting language to build logic into the template, changing the content based on data parameters.
Considerations
  • CSS styles can be embedded into HTML files. External CSS files can also be referenced in the template, if they are first uploaded as Static Resources.
  • Fixed images can be inserted into Word and PowerPoint files directly.
  • Fixed images in an HTML file need to be stored somewhere on the web, and accessed using URLs.

Use a Template to Generate a Document

When viewing a record:

  1. In the Actions list, click Print.
  2. Select the Form or Document Template to use for printing.
  3. Choose whether to print in Portrait or Landscape mode.
  4. Choose whether to save the resulting document or view it in a new window online.
  5. Click [Print].

Notepad.png

Note:
In essence, a Form is just another kind of template--only it's one that you create with the interactive Form editor. So Forms also appear in the list of Document Templates.

Working with Document Templates

Add a Document Template

A Document Template can be added to any object, except for the built-in Users object. It can use a Page stored in the platform, or it can be created using an external HTML, Word, or PowerPoint file. This section outlines the process.

To add a Document Template to an Object:

  1. Click the [New Template] button.
    The New Template page appears.
  2. Use the Template Variable Tool to get the names of variables you can use in the template:
    TemplateVariableTool.jpg
    Note:
    Template variables can be used in HTML, Word, and PowerPoint files. (In Pages stored in the platform, you use standard JSP programming techniques to access platform information, rather than template variables.)
  3. If it does not already exist, create the template.
    Follow the instructions below to add images and template variables, depending on the type of template you need to create:
  4. Provide the information in the Template Information section:
    Template Title
    The template name
    Description
    Describe the purpose of the template or other information about it.
    Ready to Use
    The default setting for the template is Yes.
    Type
    HTML - To upload an HTML, Word, or PowerPoint file stored on your local system.
    • The [Browse] button appears.
    • Click it to locate the file to upload.
    Page - To use a JSP/HTML Page stored in the platform.
    • A list of platform Pages is displayed.
    (The list does not include pages that have the Include Headers option.)
    • Choose one of the listed pages.
  5. Click [Save]

Edit a Document Template based on a Platform JSP/HTML Page

  1. Click GearIcon.png > Customization > Developer Resources > Pages > {page}
  2. Edit the page.
    Learn more: Pages
  3. If you need the names of additional variables:
    a. Click GearIcon.png > Customization > Objects > {object} > Document Templates
    b. View the template to access the Template Variable Tool:
    TemplateVariableTool.jpg

Edit a File-Based Document Template

  1. Click the Download link on the template you want to copy to your local system.
  2. Make changes to the template.
  3. If you need the names of additional variables, click the [New Template] button to access the Template Variable Tool:
    TemplateVariableTool.jpg
  4. If the New Template window is open, click [Cancel] to close it and go back to the Templates (record list) view.
  5. Click the Replace link on the template to upload the modified template.

Warn.png

Warning: Be sure to click the right link. The existing template page will be replaced by the new one.

Add an Image

In HTML, an image is referenced using a tag that has the form: <img src="...">, where the src attribute contains the path to the image. That path must be a URL of the form http://....

Insert the URL into an <img src="..."> tag. The result is a tag of the form <img src="{imageURL}/...">.

Customizing Data Sent to the Template with a Document Template Class

About Document Template Classes

Using a method defined in a Class, you can manipulate the data that a Document Template processes.

How it Works

  • The TemplateContext contains a HashMap for a record sent to the Document Template. The HashMap contains name/value pairs for the fields in that record. It is retrieved from the context using the Object name (a string).
  • To a Document Template then, a data object is simply a HashMap that is present in the TemplateContext.
  • That object is passed to a method you define. By manipulating the HashMaps it contains, you change the data that the Document Template processes. You can even add new "objects", by adding additional HashMaps, and new "related objects", by adding ArrayLists of HashMaps.
  • HashMaps and ArrayLists can be nested as deeply as needed.

Accessing Values

  • When you add a simple value to the context, the corresponding template variable is ${keyname}. So if "myParam" is the key, then $myParam inserts the corresponding value into the template.
  • If you add a HashMap, $myParam.{hashMapKey} accesses the value for some key defined in the map. Ex: $myParam.quantity
  • If you add an ArrayList, you can process the list in a loop like this:
for ($loopVariable : $myParam) {
  // work with $loopVariable here
}
  • If the ArrayList is a list of HashMaps you process the values like this:
for ($loopVariable : $myParam) {
  // work with $loopVariable.{hashMapKey}. Ex: $loopVariable.quantity
}

Coding a Method in a Document Template Class

In a Document Template, a data reference has the form $objectName.fieldname. To access, create, or modify data in your code, you will do one or more of the following operations:

  • Retrieve an object's HashMap from the TemplateContext
    TemplateContext.get("objectName");
  • Add or update a data HashMap
    TemplateContext.put("objectName", HashMap);
  • Get a field from a data HashMap
    HashMap.get("fieldName");
    Add or update a field in a data HashMap
    HashMap.put("fieldName",value);
    where value is typically a string or a nested HashMap.
  • Retrieve an ArrayList of HashMaps (one for each related-object record)
    TemplateContext.get("RelatedObjectName");

Configuring a Document Template to use a Specified Class and Method

To designate the class and method to use, when creating or editing a Document Template:

  1. Under Custom Data Source, click Enabled.
  2. In Select a Class, choose the class that has the method you want.
  3. In Select Method choose the method that does the processing you want.

The methods available to choose are public methods that have the following signature:

public {void} doSomething(TemplateContext context, String objName, String recordId) { 
}
where:
com.platform.api.TemplateContext
Is the container that the Document Template gets its data from.
String (objName)
Has the name of the object the Document Template was invoked on.
String (recordID)
Has the ID of the record on which it was invoked.
Considerations
  • Such methods generally return void, but they don't have to. Any method that takes the appropriate arguments is available, regardless of its return value.
  • A class can contain multiple processing methods, so you can do all template-related work in a single class.
  • Only one method is run, however. (You select which one.)

Accessing Lookup Target Records

Data from lookup-target records is stored as a nested map. For example, to get data for the template variable $Order.customer.name:

1. HashMap orderMap = TemplateContext.get("Order")
Gets the Order HashMap from the context.
2. HashMap customerMap = orderMap.get("customer")
Gets the lookup-target record for the customer field.
3. String name = customerMap.get("name")
Gets the customer's name.

Accessing Data in Related Records

A Document Template is always invoked on a specific record. Related-object records that look up to that record are contained in an ArrayList of HashMaps, indexed by object name. The code for obtaining and processing that kind of list looks like this:

public void chgData(TemplateContext context, String obj, String record)
{
    ArrayList<HashMap<String,Object>> listOfRecords =
        (ArrayList)context.get("SomeObject");
    if (listOfRecords == null) { listOfRecords = new ArrayList(); }
    for (HashMap<String,Object> currRecord : listOfRecords )
    {
	// Process the records in this for-each loop
    }		
}

To create an entirely new breed of related "records", create an ArrayList of the appropriate type and add it to the TemplateContext.

Examples

Changing Field Data

This example substitutes the name of the state for its abbreviation, when processing a Customer record:

public void chgData(TemplateContext context, String obj, String record)
{
    HashMap customerMap = (HashMap)context.get("Customer");
    String state = customerMap.get("state").toString();
    if ( "CA".equals(state) ) { 
        customerMap.put("state","California"); 
    }
}

Example: Adding a New Field

This example adds a new "Good Customer" field to the Customer record.

public void addData(TemplateContext context, String obj, String record)
{
    HashMap customerMap = (HashMap)context.get("Customer");
    customerMap.put("rating", "Good Customer"); }
}

After that method has run, the Document Template can use the variable $Customer.rating, just as though that field was defined in the platform object.

Example: Adding a New Object

This code creates a new ProductSupplier "object" (as far as the Document Template is concerned), and adds it to the TenantContext (context).

public void addObj(TemplateContext context, String obj, String record)
{
    HashMap<String, Object> productSupplierMap = new HashMap<String, Object>();
    productSupplierMap.put("supplierName", "Stuff R' Us");
    productSupplierMap.put("phone", "408-555-0987");
    context.put("ProductSupplier", productSupplierMap);
}

After that method has run, the Document Template can use the variable $ProductSupplier.phone, just as though the data had originated in the platform.

Example: Localizing a Comparison Value

Numeric data in the record HashMap is in the format defined by the user's locale (the User Format. To compare against a value specified in the template, either the record value must be converted to Database Format, or the comparison value must be converted to User Format, using the Java Localization Functions.

Here, the order_amount is retrieved from the Order record. That amount could have a format like "4 500,00 €" in the user's locale. This method converts the amount to the Database Format (4500.00) and stores it in the record as db_order_val:

import com.platform.api.*;

public class TemplateConversions
{

  public void convertAmount(TemplateContext context, String obj, String record)
  {
    HashMap orderMap = (HashMap)context.get("Order");
    String order_amount = orderMap.get("order_amount");
    String db_order_val = Functions.parseCurrency(order_amount);
    customerMap.put("db_order_val", db_order_val); }
  }

}

After that method has run, the Document Template can compare values that are in the same format. For example, a "big order" might be one in which the amount is greater than 1000.00. So $db_order_val can be compared against that amount.

Troubleshooting Tips

  • When testing the value of a boolean field, it's important to know that the value is a case-sensitive string that is either "Yes" or "No".
  • Velocity syntax errors cause the Velocity process to die.
  • Not all browsers display an error message when such errors occur. (Firefox does.)
  • If you're seeing what appears to be a "silent failure', try switching browsers.
  • When the error occurs in a Word or PowerPoint template, it can be difficult to pinpoint the cause of the error.
  • Converting the template to HTML helps to pinpoint the line that has the problem.
  • When a Word or PowerPoint template fails, a process instance is left running, with a corrupted document that can't be read. Subsequent attempts to open the document report an error message, and an additional process is left running.
  • On a PC, the processes can be found and killed from the Task Manager.
  • Each open process makes a temporary copy of the template, with a name like, "Template.docx (1)".
  • The existence of those undeletable template copies is a sign that processes have been left running.
  • When the processes are killed, the template copies disappear.
  • The RTA field type is not supported in document templates of type .docx/.ppt. If you use RTA field type, then when you print the document template, Rich Text Area field is printed with HTML tags.
  • When you have an error message "Word found unreadable content in <fileName>" while accessing the document, check the uploaded document template Access Permission. The file uploaded in Document Templates should be in Unrestricted mode.To check if the document is in Unrestricted Access: Click on File -Info - Protect Document - Restrict Access - Unrestricted Access.
Unrestricted access.png