Scripts Archives | Legito https://www.legito.com/knowledge-base/category/template-automation/scripts/ Learn how to use Legito’s products, and achieve more with Legito thanks to industry insights and best practice advice. Fri, 05 Apr 2024 14:34:43 +0000 en-US hourly 1 https://www.legito.com/wp-content/uploads/2016/08/cropped-legito-icon-background-32x32.png Scripts Archives | Legito https://www.legito.com/knowledge-base/category/template-automation/scripts/ 32 32 Insert Data From a Custom List https://www.legito.com/knowledge-base/insert-data-from-a-custom-list/ Sat, 25 Jul 2020 15:52:12 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18520 The post Insert Data From a Custom List appeared first on Legito.

]]>
Last review: March 2024

Goal:

Insert data from columns in a Custom List to Text Inputs in a Document or Bundled Documents based on data inserted another Text Input. The script will search your Custom List and will automatically insert the email corresponding to the inserted name.

Instructions:

  1. Create the Template tag EmployeeName and attach this tag to a Text Input in your Template where users will insert name of an employee who will, for example, sign a document on behalf of a company.
  2. Create the Template tag GetEmployeeEmail and attach this tag to a Text Input in your Template where should be a contact email to an employee who will, for example, sign a document on behalf of a company.
  3. Create a Custom List with the name Authorized Employees that will contain two columns: Employee Name and Employee Email.
  4. Insert some data to that Custom List (insert rows).
  5. Insert the below-mentioned script to the EmployeeName tag.

Script Example:

var Tags = LEGITO.documentBuilder.getTagsByName("EmployeeName");

for(var i in Tags){

if(!Tags[i].isSystem()){

var MyTag = Tags[i];

}

}

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

var TargetTags = LEGITO.documentBuilder.getTagsByName("GetEmployeeEmail");

var finder = LEGITO.documentBuilder.event.createElementFinder();

var FindEmployeeEmail = finder.findElementsByTagsAuto(TargetTags);

var AuthorizedEmployees = LEGITO.list.getListRecordsByName("Authorized Employees");

for(var i in AuthorizedEmployees){

if(AuthorizedEmployees[i][“employee-name”] == str){

for(var iii in FindEmployeeEmail)

{

FindEmployeeEmail[iii].setValue(AuthorizedEmployees[i][“employee-email”]);

}

}};

 

The post Insert Data From a Custom List appeared first on Legito.

]]>
Upper Case Letters https://www.legito.com/knowledge-base/upper-case-letters/ Sat, 25 Jul 2020 15:35:14 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18514 The post Upper Case Letters appeared first on Legito.

]]>
Last review: March 2024

Goal:

Change lower case letters inserted by a user to a Text Input to upper case letters.

Instructions:

  1. Create the Template tag (name does not matter for the script) and attach this tag to a Text Input where should be upper case letters only.
  2. Insert the below-mentioned script to that tag.

Script Example:

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

var res = str.toUpperCase();

LEGITO.documentBuilder.event.element.setValue(res);

 

The post Upper Case Letters appeared first on Legito.

]]>
Variance Function https://www.legito.com/knowledge-base/variance-function/ Sat, 25 Jul 2020 15:24:02 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18503 The post Variance Function appeared first on Legito.

]]>
Last review: March 2024

Goal:

Calculate a variance from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag Variance and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetVarianceValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the Variance tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("Variance");

 

var finder = LEGITO.documentBuilder.event.createElementFinder();
var modeValues = finder.findElementsByTagsAuto(Tags);

 

const Results = LEGITO.documentBuilder.getTagsByName("GetVarianceValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

 

let valuesArray = []
for(var i in modeValues) {
if(modeValues[i].getValue() !== null) {
valuesArray.push(parseInt(modeValues[i].getValue(), 10));
}
}

 

const getNumWithSetDec = function( num, numOfDec ){
    var pow10s = Math.pow( 10, numOfDec || 0 );
    return ( numOfDec ) ? Math.round( pow10s * num ) / pow10s : num;
};

 

const getAverageFromNumArr = function( numArr, numOfDec ){
    var i = numArr.length,
        sum = 0;
    while( i-- ){
        sum += numArr[ i ];
    }
    return getNumWithSetDec( (sum / numArr.length ), numOfDec );
};

 

const getVariance = function( numArr, numOfDec ){
    var avg = getAverageFromNumArr( numArr, numOfDec ),
        i = numArr.length,
        v = 0;
 
    while( i-- ){
        v += Math.pow( (numArr[ i ] - avg), 2 );
    }
    v /= numArr.length;
    return getNumWithSetDec( v, numOfDec );
};

 

resultElement.setValue(getVariance(valuesArray, 2).toString());

 

The post Variance Function appeared first on Legito.

]]>
Standard Deviation Function https://www.legito.com/knowledge-base/standard-deviation-function/ Sat, 25 Jul 2020 15:09:08 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18490 The post Standard Deviation Function appeared first on Legito.

]]>
Last review: March 2024

Goal:

Calculate a standard deviation from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag StandardDeviation and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetStandardDeviationValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the StandardDeviation tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("StandardDeviation");

 

var finder = LEGITO.documentBuilder.event.createElementFinder();
var modeValues = finder.findElementsByTagsAuto(Tags);

 

const Results = LEGITO.documentBuilder.getTagsByName("GetStandardDeviationValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

 

let valuesArray = []
for(var i in modeValues) {
if(modeValues[i].getValue() !== null) {
valuesArray.push(parseInt(modeValues[i].getValue(), 10));
}
}

 

const n = valuesArray.length;
const mean = valuesArray.reduce((a,b) => a+b)/n;
const s = Math.sqrt(valuesArray.map(x => Math.pow(x-mean,2)).reduce((a,b) => a+b)/n);

 

resultElement.setValue(s.toString());

 

The post Standard Deviation Function appeared first on Legito.

]]>
Mode Function https://www.legito.com/knowledge-base/mode-function/ Sat, 25 Jul 2020 15:01:32 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18482 The post Mode Function appeared first on Legito.

]]>
Last review: March 2024

Goal:

Calculate a mode amount from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag Mode and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetModeValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the Mode tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("Mode");

 

var finder = LEGITO.documentBuilder.event.createElementFinder();
var modeValues = finder.findElementsByTagsAuto(Tags);

 

const Results = LEGITO.documentBuilder.getTagsByName("GetModeValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

 

let valuesArray = []
for(var i in modeValues) {
if(modeValues[i].getValue() !== null) {
valuesArray.push(parseInt(modeValues[i].getValue(), 10));
}
}

 

function mode(numbers) {
// as result can be bimodal or multi-modal,
// the returned result is provided as an array
// mode of [3, 5, 4, 4, 1, 1, 2, 3] = [1, 3, 4]
var modes = [], count = [], i, number, maxIndex = 0;
 
for (i = 0; i < numbers.length; i += 1) {
number = numbers[i];
count[number] = (count[number] || 0) + 1;
if (count[number] > maxIndex) {
maxIndex = count[number];
}
}
 
for (i in count)
if (count.hasOwnProperty(i)) {
if (count[i] === maxIndex) {
modes.push(Number(i));
}
}
 
return modes;
}

 

resultElement.setValue(mode(valuesArray).toString());

 

The post Mode Function appeared first on Legito.

]]>
Median Function https://www.legito.com/knowledge-base/median-function/ Sat, 25 Jul 2020 14:57:59 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18473 The post Median Function appeared first on Legito.

]]>
Last review: March 2024

Goal:

Calculate a median amount from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag Median and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetMedianValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the Median tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("Median");

 

var finder = LEGITO.documentBuilder.event.createElementFinder();
var medianValues = finder.findElementsByTagsAuto(Tags);

 

const Results = LEGITO.documentBuilder.getTagsByName("GetMedianValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

 

let valuesArray = []
for(var i in medianValues) {
if(medianValues[i].getValue() !== null) {
valuesArray.push(parseInt(medianValues[i].getValue(), 10));
}
}

 

function median(values){
if(values.length ===0) return 0;

 

values.sort(function(a,b){
return a-b;
});

 

var half = Math.floor(values.length / 2);

 

if (values.length % 2)
return values[half];

 

return (values[half - 1] + values[half]) / 2.0;
}

 

resultElement.setValue(median(valuesArray).toString());

 

The post Median Function appeared first on Legito.

]]>
Average Function https://www.legito.com/knowledge-base/average-function/ Sat, 25 Jul 2020 14:36:35 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=18459 The post Average Function appeared first on Legito.

]]>
Last review: March 2024

Goal:

Calculate an average amount from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag Average and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetAverageValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the Average tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("Average");

var finder = LEGITO.documentBuilder.event.createElementFinder();
var averageValues = finder.findElementsByTagsAuto(Tags);

const Results = LEGITO.documentBuilder.getTagsByName("GetAverageValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

let valuesArray = []
for(var i in averageValues) {
if(averageValues[i].getValue() !== null) {
valuesArray.push(averageValues[i].getValue());
}
}

let arrAvg = valuesArray.reduce((a,b) => parseInt(a) + parseInt(b), 0);
let res = arrAvg / valuesArray.length;

resultElement.setValue(res.toString());

 

The post Average Function appeared first on Legito.

]]>
Documentation https://www.legito.com/knowledge-base/documentation/ Mon, 09 Mar 2020 12:40:25 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=7096 The post Documentation appeared first on Legito.

]]>
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.

The post Documentation appeared first on Legito.

]]>
Sum Function https://www.legito.com/knowledge-base/sum-function/ Mon, 09 Mar 2020 07:01:42 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=6968 The post Sum Function appeared first on Legito.

]]>
Last review: March 2024

Goal:

Calculate a sum amount from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag Sum and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetSumValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the Sum tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("Sum");

var finder = LEGITO.documentBuilder.event.createElementFinder();
var sumValues = finder.findElementsByTagsAuto(Tags);

const Results = LEGITO.documentBuilder.getTagsByName("GetSumValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

let valuesArray = []
for(var i in sumValues) {
if(sumValues[i].getValue() !== null) {
valuesArray.push(sumValues[i].getValue());
}
}

let arrSum = valuesArray.reduce((a,b) => parseInt(a) + parseInt(b), 0);

resultElement.setValue(arrSum.toString());

 

The post Sum Function appeared first on Legito.

]]>
Script Editor https://www.legito.com/knowledge-base/script-editor/ Tue, 03 Mar 2020 18:23:46 +0000 https://new-blog.legito.com/?post_type=epkb_post_type_1&p=6068 The post Script Editor appeared first on Legito.

]]>
Last review: March 2024

Please contact us at automation@legito.com for access to this feature.

The post Script Editor appeared first on Legito.

]]>