How to create a form?

Form

Package@schukai/component-form
Importimport {Form} from "https://cdn.jsdelivr.net/npm/@schukai/[email protected]/dist/modules/form.js";

Usage

The Form component allows the user to create a form and in interaction with a datasource to change data.


// create element
const form = document.createElement('monster-form');

Input controls

A form needs input fields. These can be easily defined within the tag. Either via Javascript directly or via the markup.


const input = document.createElement('input')
input.setAttribute('name','field');
form.appendChild(input);

via markup


<monster-form>
    <input name="field">
</monster-form>

The forumlar field ➊ are included as slotted elements in the shadowroot ➋.

Datasource

One of the more interesting features of the form is the ability to connect the form to a data source. A datasource has a simple API to read and write an object (see Monster Framework under Datasources).

In this example we use a RestAPI datasource, but other datasources work as well. The example url httpbin.org is a service that provides a simple api with data. This is for this example only. You can of course specify your own api here.


const datasource =  new RestAPI({
  url: 'https://httpbin.org/get'
},{
  url: 'https://httpbin.org/post'
});
form.setOption('datasource', datasource)

In order to see the data as a value in the input field, we must specify the attribute data-monster-attributes.


const input = document.createElement('input')
input.setAttribute('name','field');
input.setAttribute('data-monster-attributes','value path:headers.Host');
form.appendChild(input);
    

Now we have to report the data back to the datasource. For this we use the attribute data-monster-bind. In this example we write the value in the same field, but we can also choose another field if for example the POST api has a different structure.


input.setAttribute('data-monster-bind','path:headers.Host');
    

Actions

What is a form without action? To be able to send the changed data we can add a button.


const button = document.createElement('monster-state-button');
// let's give the button a text
button.setOption('labels.button','click!')
// this attribute ensures that the form sets an action handler in the button.
button.setAttribute('data-monster-datasource-handler','write')
form.appendChild(button);
    

If we now click on the button, the modified dataset will be sent to the url previously specified in the RestAPI datasource.

Layout

The select control can be customized to your own needs. For this purpose, the control can be designed via css.

The different parts of the control can be designed using CSS. Since the internals of the component are in a shadow tree, access is via css pseudo-element parts.


#select1::part(popper) {
    background-color: white;
}

The individual parts are shown in the following picture.