Example: build simple form
Problem: we want to generation complex form and saving it result.
From last lesson we getting the structure "population" and added fields "value" for write throw POST request.
It will be like this:

Go to your plugin, and add new "web component" with 2 parameters: endpoint for reading data and title for show title on your simple form:

Add init script:
function(instance, context) {
div = $('<form id="myForm"></form>');
instance.canvas.append(div);
}
Then add "Update" script
function(instance, properties, context) {
var ctx = document.getElementById('myForm');
var layout = $('myForm') // get form by id
var data = context.endpoint || []
var title = context.title
// reading data by api endpoint for set your future select
var data = context.endpoint || []
// replace below URL to your api-endpoint for saving data
var endpointForSave = "https://api.directual.com/good/api/v5/data/population/getPopulation?appID=2...b65&sessionID="
//build you form
$form = $("#myForm");
$form.empty() //remove all inputs
$form.append('<h1>' + title + '</h1>');
$form.append('<input type="text" value="you name" name="name">');
$form.append('<select id="population" name="value"></select>');
data.forEach((datum)=>{
$('#population').append('<option value="' + datum.value + '">' + datum.value + '</option>');
})
var send = $("<button>Send data to server</button>");
send.click(()=>{
//prepare json object to send server
var formdata = $form.serializeArray();
var data = {};
$(formdata).each(function(index, obj){
data[obj.name] = obj.value;
});
$form.empty()
$form.append('<h1>' + title + '</h1>');
$form.append('<span>sending data: ' + JSON.stringify(data) + ' to server</span>');
fetch(endpointForSave, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(()=>{
$form.empty()
$form.append('<h1>' + title + '</h1>');
$form.append('<span>Congratulations, the data has been sent to the server</span>');
})
})
$form.append(send);
}
Insert step with you component to page and setup it.

Open you page, and try to fill and send your form to directual.

Last modified 1yr ago