Example of using form field values in the handler
In the First steps: "Hello, World!" plugin article, we gave an example of a plugin handler that outputs a page with text. Here, we will give an example of how to add an editable field with a button to send data and use the received data in the handler.
Suppose you have created an XML description of the plugin and a handler file as described in the link above. In case you want to show the field and button only if the user has not entered anything yet. The contents of the handler file /usr/local/mgr5/addon/helloworld.xml
should look like this:
#!/bin/bash
name=$PARAM_name
if [ -z "$name" ]
then
read -r -d '' formfields <<-EOM
<field name="name">
<input name="name" type="text" />
</field>
EOM
read -r -d '' formbuttons <<- EOM
<buttons>
<button type="ok" action="helloworld" name="ok"/>
</buttons>
EOM
else
read -r -d '' formfields <<- EOM
<field name="helloworld_field">
<textdata name="helloworld_message" type="msg" />
</field>
EOM
fi
cat << EOM
<?xml version="1.0" encoding="UTF-8"?>
<doc lang="ru" func="helloworld">
<metadata type="form">
<form>
${formfields}
${formbuttons}
</form>
</metadata>
<messages>
<msg name="title">Плагин Hello, world!</msg>
<msg name="name">Введите ваше имя</msg>
<msg name="helloworld_message">Hello, ${name}!</msg>
<msg name="msg_ok">OK</msg>
</messages>
</doc>
EOM
If the environment variable PARAM_name is empty or does not exist, we show the input field and the button, in this case the <form> element in XML at the output of the handler looks the following way:
<form>
<field name="name">
<input name="name" type="text" />
</field>
<buttons>
<button type="ok" action="helloworld" name="ok"/>
</buttons>
</form>
When the form is submitted by clicking the OK button, the text entered in the name field is passed to the handler in the PARAM_name environment variable, and we display the entered text as part of the text field:
<form>
<field name="helloworld_field">
<textdata name="helloworld_message" type="msg" />
</field>
</form>
The text for the text field is passed in the <msg name="helloworld_message">
element.
Read more about the XML structure returned by handlers in Structure and functionality of plugins.
For an example of the same topic in PHP, Python, and Node.js, see Примеры плагинов на PHP, Python, Node.