Writing functions
In this chapter is explained how you can create loops in your Penbox form.
At Penbox, we are proud to say that we can handle complex business logic. With a traditional form builder, you often have the possibility to create conditional logic and question branching. Those features can meet a range of business requirements, but you may find yourself limited at some point.
With Penbox, you can write functions directly within pen-script. Here are a few examples of stuff you can do:
- Write advanced conditions using the
:if
- Create loops using
:map
,:array
or:object-entries
- Loop through a object or a list of objects
- Create conditionary choices in
radio
orcheckboxes
elements
...
In this section, we will guide you through the basic of writing functions within Penbox and explain you some use cases.
Writing a function
Functions in pen-script are objects with the attributes starting with :
. When writing a function in pen-script, Penbox will evaluate the function in real-time and replace the object with the result of the function.
Example: the loop function :array
takes as argument :fill
. The value of :array
must be an integer who will determines the number of loops, while the value of :fill
will be evaluated with for each loop.
Note: if you want to easily test some functions in the studio, you can write them in
variables
attribute and see the result of the evaluation in the Variable tab
Let's write this function in the variables:
{
"variables": [
{
"test": {
":fill": "{@index}",
":array": 5
}
}
]
}
The content of the variable test
is now a list of elements from 0 to 4.
For informatio, the following variables are accessible in the :fill
context:
@first:
boolean, true if first item@index
: current index, starting counting at 0@position
: current position. Equals to index + 1@last
: boolean, true if last item
Using a function to create dynamic elements or steps
If you want to ask how many children someone has and want to know the first name and last name of each child.
- Create an element with the question: "How many children do you have?
- Use the answer of this question to determine the length of the array:
{ ":array": "{data.amount_children}" }
- Use the variable {@position} in the key and label of the elements to define the several children
Example in code:
{
"steps": [
{
"label": "Children",
"elements": [
{
"key": "data.amount_children",
"type": "text",
"title": "How many children do you have?",
"format": "number"
},
{
":fill": [
{
"type": "paragraph",
"content": "Child {@position}"
},
{
"key": "data.first_name_{@position}",
"type": "text",
"label": "First name child {@position}",
"pattern": "/^[a-z0-9]{2,5}$/i"
},
{
"key": "data.last_name_{@position}",
"type": "text",
"label": "Last name child {@position}",
"pattern": "/^[a-z0-9]{2,5}$/i"
}
],
":array": "{data.amount_children}"
}
]
}
]
}
Result in Penbox form:
Updated over 1 year ago
In the next chapter we'll introduce you to other common pen-script expressions.