Table of Contents

Code Set

Pau Sanchez Updated by Pau Sanchez

This block is only available for web chatbots

The Code Set block, allows to set up the value of a Landbot variable using Javascript. It avoids the need to use a user input (buttons, text question...) to be able to use immediately the new value created.

How to use it

Select Landbot variable to set

First of all we need to select (or create) the Landbot variable that we want to set using the Code set bloc

Use Landbot variable

If we are using values collected previously we need to set Javascript variables with those values:

In this example, we are using @value1 and @value2, that are numbers.

Returning value

Finally, need to return the value we want to set:

Always we need to end with the "return" action.

Here is how it would look like this example in the builder:

And the chat:

Actions to avoid

- Do not use to delay the bot using setTimeout

- Do not try to set up more than one variable at once

- If you are working with Objects that might contain boolean values (true false) use template literals to set Javascript variables

Example: let object = `@{array}`

- If a Landbot variable is not set, the block will fail and the bot will stop

- Do not return directly Landbot variables or operate like in the example below:

Examples

Below are a number of examples of how it can be used:

Simple Math operation

Get current year

Generate HTML for a Table

let myArray = @array;
let table = '<table><tr><th>Item</th><th>Price</th></tr>';
for (let i = 0; i < myArray.length; i++) {
let row = `<tr>
<td>${myArray[i]['item']}</td>
<td>${myArray[i]['price']}</td>
</tr>`;
table = table + row;
}
table += '</table>';
return table;

Check day of the week and return if business is open or closed

let status;
switch (new Date().getDay()) {
case 0:
status = "Closed";
break;
case 1:
status = "Open";
break;
case 2:
status = "Open";
break;
case 3:
status = "Open";
break;
case 4:
status = "Open";
break;
case 5:
status = "Open";
break;
case 6:
status = "Closed";
}
return status;

Replace True, False, null values from an array of objects

let JsonStr = "@{array}";

let JsonStrReplaced = JsonStr.replaceAll('None','"None"').replaceAll('True','"true"').replaceAll('False','"false"').replaceAll("'",'"');
let cleanArray = JSON.parse(JsonStrReplaced);

return cleanArray

How did we do?

Javascript in Landbot v2

Contact