Search Knowledge Base by Keyword

Documentation

Last review: March 2024

TagScripts

For advanced usage of Templates and Documents, Legito offers an integrated script engine that enables running a secure subset of TypeScript code as a reaction on one of the supported document events. Scripts can read the document, input values, modify them, and even use REST calls to obtain data from an external resource.

 

Introduction

 

Tags in a document and calling the script

In the document editor, we have an option to tag elements. When you do so, you can bind the script to the tag and you can manipulate, change values, and get values via your script. So we will make a quick script that takes the input value from the text input element, does an operation with the data, and then shows the data in the output text field.

 

Create a document with these fields

We will create one “Text Input” and one “Text” element.

Then when you click on the element, you will see “Tags” in your top menu which after you select, will allow you to set a custom tag for the selected element.

Now do the same for the output text field and name it “outputField1” etc.

Publish the template

 

Create and access the script

In your workspace, go to settings ⇒ Template Tags & Scripts.

If you have done everything in the first part, you will see these tags:

Now select the InputField1 and click “Edit scripts” ⇒ click on “Add” in the top right corner. Name your script as you like, I will go with “IOScriptTemplate”. IO means “Input/Output”.

Click on “Create Script”.

The Script is now bound to the inputField1 element. When we insert or edit the content of that element, it will automatically run the script.

 

Scripting environment (IDE) and usage

Before we can run anything we wrote, we always need to click on Publish at the right bottom of the IDE.

Test script:

Opens the template in which the script is bound to the tag. If you then proceed to execute the script (in our case, write something to the input field), it will call the script and after going back to the IDE we can check the debugger.

Open debugger:

We can see there all the test runs we have made and their logs and errors.

 

Writing the script

In the script, we can now refer to the all elements that have tags in the document.

First, we will create Element Finder using

const elementFinder = LEGITO.documentBuilder.event.createElementFinder();

Now we can use the element finder to locate the elements with tags in the document. First, we want to get the value from the input field which is also the element that is calling this script. But first, we need to get the tags:

const tags = LEGITO.documentBuilder.getTagsByName("inputField1");

After we have the tags in constant tags, we can find all the elements with that tag (in our case it’s only one, but you can get multiple elements with the same tag).

const listOfElements = elementFinder.findElementsByTagsAuto(tags);

As you can see we now have a list of all elements with our tag “inputField1”, but there is only one element in the list (it’s still a list but with a single element).

To access the value of the input we need to call the function getValue(). But remember that it is a list, so we first need to tell the script to get the value of 1st item in that list.

var valueOfInput = listOfElements[0].getValue()

Now we have a value user inputted in the input field stored in variable valueOfInput. Next, we will want to return it to the document and show the value in outputField1.

So we will need to find the output element the same as before:

const tagsOutput = LEGITO.documentBuilder.getTagsByName("outputField1");
const listOfOutputElements = elementFinder.findElementsByTagsAuto(tagsOutput);

And then set the value of the element via the function setValue().

listOfOutputElements[0].setValue(valueOfInput);

Again we are telling the script to change the value of 1st item in the list (we only have one item in the list) and then set its value.

If you now click on the Test script and insert your value to the Text Input field it will instantly show it in the text below.

If it does not work, you can check the Debugger and look for errors. If it runs properly it should look like this:

 

Debugging

If you want to check values in the middle of your script you can use LEGITO.debug.log();

LEGITO.debug.log(listOfOutputElements);

When you test your script you can then go to “Open debugger” and inspect what you outputted to the debug log.

For instance, this is listOfOutputElements and you can check all its properties.

 

HTTP example

For advanced usage of Templates and Documents, Legito offers an integrated script engine that enables running a secure subset of TypeScript code as a reaction on one of the supported document events. Scripts can read the document, input values, modify them, and even use REST calls to obtain data from an external resource.

Script API documentation can be found here: https://emea.legito.com/ts-api/definition/

Example of a simple TagScript that fills a value into a TextInput from the Internet using REST API:

// create finder
const finder = LEGITO.documentBuilder.event.createElementFinder();//create REST client
const client = LEGITO.restClient.create();// get a response from the endpoint
const response = client.get('https://mocki.io/v1/7558aae9-e7a1-4ec3-9ed3-5a3d4b78e3dc').data;// find element by tag
const output = finder.findElementsByTagsAuto([LEGITO.documentBuilder.getUserTagByName('result')])[0];// log to verify
LEGITO.debug.log(output);// read value from REST response and store in the document
output.setValue("" + response['company']);

Explanation:

For finding elements in the document there is a finder that needs to be obtained from LEGITO.documentBuilder.event.Then a REST client is created.

 

TagScript Documentation

Generated documentation here https://emea.legito.com/ts-api/definition/

 

Finders

Introduction

Finders in LEGITO’s documentBuilder are tools that aid developers in pinpointing and interacting with elements in LEGITO documents. They’re especially potent for tasks that require repetitive or iterative operations on multiple elements.

Using Finders

Create element finder

const elementFinder = LEGITO.documentBuilder.event.createElementFinder();

Retrieving Tags

Utilize getTagsByName to element tags.

const tags = LEGITO.documentBuilder.getTagsByName("tagOfTheElements");

Finding Elements Automatically

Use findElementsByTagsAuto with a predefined list of target tags to retrieve the required elements:

const finder = LEGITO.documentBuilder.event.createElementFinder();
const tags = LEGITO.documentBuilder.getTagsByName("tagOfTheElements");
const listOfElements = finder.findElementsByTagsAuto(tags);

 

Methods

 

1. findElementsBySystemName

Finds elements by their system name in specific documents based on optional parameters.

  • Parameters:
    • name (string): Name of the element.
    • document (IDocument): Optional parameter. The document in which to search. Default: null.
    • findInOtherDocuments (boolean): Optional parameter. Whether or not to search in other documents. Default: true.
  • Returns: A list of elements (type: __type).

 

2. findElementsByTableColDocument

Finds elements but only within the same table and column as the element that called the script.

  • Parameters:
    • searcherTags (__type): Tags to use for searching.
    • invalidSearchTags (__type): Optional parameter. Tags to exclude from the search. Default: [].
    • errorCallback (function): Optional callback function for errors. Default: null.
  • Returns: A list of elements (type: __type) or null.

 

3. findElementsByTableRowDocument

Finds elements but only within the same table and row as the element that called the script.

  • Parameters:
    • searcherTags (__type): Tags to use for searching.
    • invalidSearchTags (__type): Optional parameter. Tags to exclude from the search. Default: [].
    • errorCallback (function): Optional callback function for errors. Default: null.
  • Returns: A list of elements (type: __type) or null.

 

4. findElementsByTagsAuto

Automatically finds elements by their associated tags in the document based on preferred mode (global, context, tableRow, tableCol). You can set or get the preferred mode with the functions noted below.

  • Parameters:
    • searcherTags (__type): Tags to use for searching.
    • invalidSearchTags (__type): Optional parameter. Tags to exclude from the search. Default: [].
    • errorCallback (function): Optional callback function for errors. Default: null.
  • Returns: A list of elements (type: __type) or null.

 

5. findElementsByTagsContext

Finds elements by tags within the context of the element that called the script.

You can change the context by the method setContextElement explained below.

  • Parameters:
    • searcherTags (__type): Tags to use for searching.
    • invalidSearchTags (__type): Optional parameter. Tags to exclude from the search. Default: [].
    • errorCallback (function): Optional callback function for errors. Default: null.
  • Returns: A list of elements (type: __type) or null.

 

6. findElementsByTagsDocument

Finds elements by tags within a document where it is called.

  • Parameters:
    • searcherTags (__type): Tags to use for searching.
    • invalidSearchTags (__type): Optional parameter. Tags to exclude from the search. Default: [].
    • errorCallback (function): Optional callback function for errors. Default: null.
  • Returns: A list of elements (type: __type) or null.

 

7. findElementsByTagsGlobal

Globally finds elements by their associated tags even in the whole document structure. Like this:

  • Parameters:
    • searcherTags (__type): Tags to use for searching.
    • invalidSearchTags (__type): Optional parameter. Tags to exclude from the search. Default: [].
    • errorCallback (function): Optional callback function for errors. Default: null.
  • Returns: A list of elements (type: __type) or null.

 

8. findStaticElementBySystemName

Finds a static element by its system name in the specified document.

Static – element is not repeated, for info about repeating see method findElementsBySystemName

  • Parameters:
    • name (string): Name of the element.
    • document (IDocument): Optional parameter. The document in which to search. Default: null.
    • findInOtherDocuments (boolean): Optional parameter. Whether or not to search in other documents. Default: true.
  • Returns: The found IDocumentElement or null.

 

9. getContextElement

Gets the current context element.

  • Returns: The current context IDocumentElement or null.

 

10. getPreferredSearchCounterMode

Retrieves the preferred search counter mode.

  • Returns: A string indicating the mode.

 

11. getPreferredSearchMode

Retrieves the preferred search mode.

  • Returns: A string indicating the mode.

 

12. isEnableCounterElements

Indicates if the counter elements are enabled.

  • Returns: true if enabled, false otherwise.

 

13. isEnableInvisibleElements

Indicates if the invisible elements are included in the search.

  • Returns: true if included, false otherwise.

 

14. setContextElement

Sets the context element for the finder.

  • Parameters:
    • contextElement (IDocumentElement): The element to set as context.
  • Returns: The IElementFinder instance (for method chaining).

 

15. setEnableCounterElements

Enables or disables the counter elements.

Implicit enabled for context mode of tag searching.

  • Parameters:
    • enableCounterElements (boolean): Whether to enable the counter elements.
  • Returns: The IElementFinder instance (for method chaining).

 

16. setEnableInvisibleElements

Sets whether the finder should include invisible elements in the search.

  • Parameters:
    • enableInvisibleElements (boolean): Whether to enable searching for invisible elements.
  • Returns: The IElementFinder instance (for method chaining).

 

17. setPreferredSearchCounterMode

Sets the preferred search counter mode.

  • Parameters:
    • preferredSearchCounterMode (string): Optional parameter. The mode to set. Default: “context”.
  • Returns: The IElementFinder instance (for method chaining).

 

18. setPreferredSearchMode

Sets the preferred search mode. The modes are:

  • “global”
  • “document”
  • “context”
  • “tableRow”
  • “tableCol”
  • Parameters:
    • preferredSearchMode (string): Optional parameter. The mode to set. Default: “global”.
  • Returns: The IElementFinder instance (for method chaining).

Skipping System Tags

If you need to avoid system tags and only work with custom tags:

for(var i of tags) {
if(!tags[i].isSystem()) {
var myTag = tags[i];
}
}

Retrieving the Value of an Event Element

Gets the value of the element that is bound to the script.

var str = LEGITO.documentBuilder.event.element.getValue();

 

Cache

A cache can be accessed in any document or script. Its content can be used for the whole Workspace.

 

Methods

1. save

This function saves data to the cache.

//expiration date is in format "YYYY-MM-DDTHH:MM:SSZ" or "+3minutes"
LEGITO.cache.save('key', value, 'expirationDate');
//like this:
LEGITO.cache.save("apiOutput", response.data, "2020-12-31T23:59:59Z");
  • Parameters:
    • key: string: The identifier you want to use for the data you’re caching.
    • data: any: The actual data you’re saving to the cache.
    • expiration: string (optional): A string representation of when the cached data should expire. If not provided, it defaults to null, which might mean that the data never expires or that it uses some default expiration setting.
  • Returns:
    • void: Again, this means the function doesn’t return any value. Its primary purpose is to perform the save operation.

2. load

This function retrieves data from the cache.

var value = LEGITO.cache.load('key');
  • Parameters:
    • key: string: The identifier for the cached data you want to retrieve.
  • Returns:
    • any: The data associated with the provided key, or potentially undefined if the key doesn’t exist in the cache.

3. remove

This function deletes data from the cache.

LEGITO.cache.remove('key');
  • Parameters:
    • key: string: The identifier for the cached data you want to delete.
  • Returns:
    • void: This means the function doesn’t return any value. Its primary purpose is to perform the delete operation.

RestClient

The RestClient is a utility class provided by LEGITO for making HTTP requests. An instance can be created with the LEGITO API and be used to perform various HTTP methods. API calls return RestClientResponse (explained below).

Usage

const restClient = LEGITO.restClient.create();

How to make API call

Create API key in Legito Web Application: go to Settings ⇒ API ⇒ Generate API Keys ⇒ Create Token

 

How to get API token automatically in the script

API URL where you will get JTW Token for API calls from script to Legito API: https://n8n.emea.legito.com/webhook/41baf2ac-cb33-4dc7-8e55-55ef17272ca7

const client = LEGITO.restClient.create();const apiKey = 	"your_api_key";
const privateKey = "your_private_key";
const urlToGetToken = "<https://n8n.emea.legito.com/webhook/41baf2ac-cb33-4dc7-8e55-55ef17272ca7>"var headers = {
"x-api-key": apiKey,
"x-private-key": privateKey
}var parameters = {}const token = client.get(urlToGetToken, parameters, headers).dataRaw;

Now use the token in the script.

You always have to use both parameters and headers if you want to call the function with one of them. The other can be empty.

const client = LEGITO.restClient.create();// Replace this with your actual token. Ideally, this would be fetched or generated securely.
const token = "token_you_just_created_or_see_below";// Set up headers for the request
const headers = {
"Authorization": "Bearer " + token,
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br"
};//set up parameters
const parameters = {
};//make API call and save the response (get list of users in this case)
const response = client.get("<https://emea.legito.com/api/v6/user>", parameters, headers);

 

Rest Client Methods

https://en.wikipedia.org/wiki/HTTP#Request_methods

1. get

Makes a GET request to the specified URL.

Parameters:

  • url: string: The endpoint URL.
  • parameters: __type (optional): Query parameters for the request. Default is an empty array.
  • headers: __type (optional): HTTP headers to be sent with the request. Default is an empty array.

Returns:

  • RestClientResponse: The response from the request.

2. post

Makes a POST request to the specified URL.

Parameters:

  • url: string: The endpoint URL.
  • parameters: __type (optional): Body data for the request. The default is an empty array.
  • headers: __type (optional): HTTP headers to be sent with the request. The default is an empty array.

Returns:

  • RestClientResponse: The response from the request.

3. put

Makes a PUT request to the specified URL.

Parameters:

  • url: string: The endpoint URL.
  • parameters: __type (optional): Body data for the request. The default is an empty array.
  • headers: __type (optional): HTTP headers to be sent with the request. The default is an empty array.

Returns:

  • RestClientResponse: The response from the request.

4. patch

Makes a PATCH request to the specified URL.

Parameters:

  • url: string: The endpoint URL.
  • parameters: __type (optional): Body data for the request. The default is an empty array.
  • headers: __type (optional): HTTP headers to be sent with the request. The default is an empty array.

Returns:

  • RestClientResponse: The response from the request.

5. del

Makes a DELETE request to the specified URL.

Parameters:

  • url: string: The endpoint URL.
  • parameters: __type (optional): Query parameters for the request. The default is an empty array.
  • headers: __type (optional): HTTP headers to be sent with the request. The default is an empty array.

Returns:

  • RestClientResponse: The response from the request.

6. head

Makes a HEAD request to the specified URL.

Parameters:

  • url: string: The endpoint URL.
  • parameters: __type (optional): Query parameters for the request. The default is an empty array.
  • headers: __type (optional): HTTP headers to be sent with the request. The default is an empty array.

Returns:

  • RestClientResponse: The response from the request.

7. setOption

Sets a specific option for the RestClient.

Parameters:

  • key: string: The name of the option.
  • value: any: The value for the option.

Returns:

  • void: The method does not return a value.

RestClientResponse Class

RestClientResponse is a class that represents the response from a RESTful request made using the RestClient class. It provides methods and properties to inspect and process the result of a REST call.

Properties

code

  • Type: number
  • Description: This property holds the HTTP status code of the response.

data

  • Type: any
  • Description: Contains the parsed response data. The exact structure depends on the response’s content.

dataRaw

  • Type: string
  • Description: This property contains the raw string representation of the response data.

error

  • Type: string
  • Description: Contains any error messages or details associated with the response. If no errors occur, this will be an empty string.

isValidJson

  • Type: boolean
  • Description: Indicates whether the response data is a valid JSON format.

 

Methods

1. getScriptDebugInfo

  • Returns: __type
  • Description:

This function seems broken. You can get more info using:

const response = client.get("<https://emea.legito.com/api/v6/user>", parameters, headers);
LEGITO.debug.log(response);

2. isSuccess

  • Returns: boolean
  • Description: Determines whether the REST call was successful by checking the HTTP status code. Returns true if the call was successful; otherwise, false.

New objects for Scripts

To enhance the functionality of the Scripts attached to Template Tags applied to your Legito Templates, the following new objects are available for inclusion in your Scripts:

  • documentBuilder.event
  • LEGITO.currentUser
    • Action-triggering User Name: LEGITO.currentUser.name
    • Action-triggering User Email: LEGITO.currentUser.email
    • Action-triggering User ID: LEGITO.currentUser.id
    • Action-triggering User Position: LEGITO.currentUser.position
    • Action-triggering User Custom Data: LEGITO.currentUser.customData

Action-triggering User is a user that performed the action in the Legito’s user interface, for example a user that clicked to the Save button .

  • LEGITO.defaultApiUser objects
    • Default API User NameLEGITO.defaultApiUser.name
    • Default API User Email LEGITO.defaultApiUser.email
    • Default API User ID LEGITO.defaultApiUser.id
    • Default API User Position LEGITO.defaultApiUser.position
      Default API User Custom Data LEGITO.defaultApiUser.customData

Default API User is the user that is defined in the API section of the Workspace Settings.