This example shows a dynamic form with an Add button and a Remove button. The form starts with one input field and lets users add or remove lines as needed.
Phase: Init
Groovy
form.createButtonEntry("Add Line")
.setLabel("Add")
.onClick()
.buildFormInput()
form.createStringUserEntry("Line1")
.setLabel("Line 1")
.buildFormInput()
form.createButtonEntry("Remove")
.setLabel("Remove")
.onClick()
.buildFormInput()
This code creates the initial form: an Add button, one text input (Line1), and a Remove button. Both buttons use onClick() so the form can react when the user clicks them.
Phase: OnClick
Groovy
def changes = [:]
def maxId = input.keySet()
.collect { (r = it =~ /Line(\d+)/) ? r.group(1) as int : null }
.max() ?: 0
if (form.sourceInputName() == "Add Line") {
if (maxId != null) {
def nextId = maxId + 1
def newInput = form.createTextUserEntry("Line" + nextId)
.setLabel("Line " + nextId)
.buildContextParameter()
form.insertAfter("Line" + maxId, newInput)
}
} else if (form.sourceInputName() == "Remove") {
if (maxId > 1) {
form.updateInput("Line" + maxId).remove()
}
}
return changes
This code finds the highest existing line number (Line1, Line2, and so on). If the user clicks Add, it creates the next input and inserts it after the last one. If the user clicks Remove, it deletes the last input, but keeps at least Line1 in the form.
Summary
Use this pattern when the number of inputs is not known in advance and users need to add lines dynamically during configuration.