Form
A form control
import { Form } from "@schukai/monster/source/components/form/form.mjs";Introduction
The Form component is a sophisticated web control from the Monster library that organizes and manages form data effectively. This component is designed to handle complex form interactions, ensuring data consistency and validation across various form fields. It is an ideal choice for applications requiring detailed data collection and validation.
Key Features
- Data Binding and Validation: Automatically manages data binding between form fields and data sources, and validates data using built-in validation mechanisms.
- Event Handling: Provides comprehensive event handling options that trigger data write-backs and validation on various user interactions.
- Customizable Appearance: Offers extensive options for customization, allowing the form and its elements to be styled according to application design requirements.
- Advanced Configuration: Supports advanced configuration options for features like mutation observation, which monitors changes in form elements, and write-back features for real-time data synchronization.
- Accessibility: Built with accessibility in mind to ensure that all users can interact with the form effectively.
Improving the user experience
The Form component enhances user experience by providing a structured and error-free data entry process. It simplifies form interactions by automatically managing data bindings and validations, reducing the likelihood of user errors and improving data integrity. This component ensures a smoother and more reliable interaction for users, thereby enhancing overall user satisfaction.
Efficiency in the development process
Incorporating the Form component into web applications streamlines the development process by reducing the amount of code required for form management. Its reusable design and built-in functionalities reduce development time and effort, allowing developers to focus more on core application features. The component's design ensures that developers can easily adapt it to various application needs, promoting efficiency and scalability.
Building Blocks
- Datasource: REST or DOM datasource stores data and triggers updates.
- Form: Reads and writes values to the datasource.
- Controls: Inputs or custom elements with
data-monster-bindanddata-monster-attributes. - Status and Save: Optional controls for UX feedback and write actions.
- Dataset View: Optional debugging view of the live dataset.
Typical Setup
<monster-datasource-rest
id="ds-user"
data-monster-option-read-url="/user.json"
data-monster-option-write-url="/user.json"
data-monster-option-response-path-validationErrors="meta.validationErrors"
data-monster-option-response-path-validationMessage="meta.message"
data-monster-option-validation-map='{"name":"path:data.name","email":"path:data.email"}'
></monster-datasource-rest>
<monster-datasource-status
data-monster-option-datasource-selector="#ds-user"
></monster-datasource-status>
<monster-datasource-save-button
data-monster-option-datasource-selector="#ds-user"
></monster-datasource-save-button>
<monster-form
data-monster-option-datasource-selector="#ds-user"
data-monster-option-labels='{"VAL_REQUIRED":"Please enter a name"}'
>
<monster-field-set>
<label>Name</label>
<input
data-monster-attributes="value path:data.name"
data-monster-bind="path:data.name"
>
<label>Email</label>
<input
data-monster-attributes="value path:data.email"
data-monster-bind="path:data.email"
>
</monster-field-set>
</monster-form>
Control Binding Rules
Controls connect to the model using two mechanisms:
- Read model to UI:
data-monster-attributes="value path:..."writes data into the control. - Write UI to model:
data-monster-bind="path:..."writes control values back to the model.
The form listens to input events and writes to the datasource. The save button compares current values to origin values and shows the change counter.
Datasource Flow
Read
datasource.read()fetches data.- The datasource updates its internal model.
- The form (via dataset base) updates the controls.
Write
- User edits a control.
- Form writes back into the model.
- Save button diff detects changes.
datasource.write()sends data to the API.
Validation Flow
When the API returns validation data, the form sets setCustomValidity() on the matching control, adds data-monster-validation-error, and shows a monster-context-error icon in the label.
{
"meta": {
"status": 400,
"message": "Input data is invalid",
"validationErrors": {
"name": {
"code": "VAL_REQUIRED",
"message": "Name is required"
}
}
}
}
Use data-monster-option-validation-map to map API keys to bind paths and data-monster-option-labels to override messages by validation code.
Dynamic Controls (Late Inserts)
Do not append raw DOM nodes directly; those nodes will not be wired by the updater. Use data-monster-insert and a <template> instead.
<template id="field">
<label data-monster-replace="path:field.label"></label>
<input
data-monster-attributes="value path:field.value"
data-monster-bind="path:field.value"
>
</template>
<monster-field-set>
<!-- static fields here -->
</monster-field-set>
<monster-field-set data-monster-insert="field path:data.dynamicFields"></monster-field-set>
Common Pitfalls
- No binding updates for dynamic fields: Use
data-monster-insert. - Validation icon appears on the wrong field: Labels and controls do not match.
- Save counter not increasing: Controls lack
data-monster-bindor are outside the dataset.
Demo Reference
The live demo for this setup is in:
development/issues/open/348.htmldevelopment/issues/open/348.mjs
Form Simple
Javascript
/** this example does not use an extra script **/HTML
/** this example does not use an extra html file **/Stylesheet
/** no additional stylesheet is defined **/Component Design
The monster-form component is a container for grouping form elements. Built using the Shadow DOM, it encapsulates the form's structure and styling, ensuring isolation and consistency. Developers can use this component to wrap form controls while maintaining control over styling and layout.
Shadow DOM and Accessibility
The use of the Shadow DOM ensures that the internal form structure is isolated from the global styles of the application. This encapsulation prevents unintended interference from external CSS or scripts while providing a predictable layout for the form.
The component follows accessibility standards by allowing developers to use native form elements such as input, select, and textarea inside the form. It also supports reportValidity for validating child form elements.
Customizing Through Exported Parts
The monster-form component exposes internal parts for styling using the part attribute. This allows targeted CSS customization of the form container and its related elements.
Available Part Attributes
control: Represents the main control wrapper around the form.form: Targets the internal form element, allowing you to apply custom styles to the form layout.
Below is an example of how to customize the form using CSS:
monster-form::part(form) {
border: 1px solid #ccc;
padding: 20px;
border-radius: 6px;
background-color: #fafafa;
}
monster-form::part(control) {
margin: 10px 0;
display: flex;
flex-direction: column;
}
Explanation of the Example
monster-form::part(form): Styles the internal form element with padding, a border, and a light background.monster-form::part(control): Adds spacing and organizes the main form container into a column layout.
Accessibility
The monster-form component is designed to ensure accessibility for all users:
- Native form elements retain their default behaviors and semantics for screen readers.
- Keyboard navigation works seamlessly within the form container.
- The
reportValiditymethod allows developers to validate child elements programmatically, ensuring proper error feedback.
By providing a well-structured form container and supporting accessible form controls, the monster-form component ensures an inclusive user experience.
HTML Structure
<monster-form></monster-form>JavaScript Initialization
const element = document.createElement('monster-form');
document.body.appendChild(element);Exported
FormDerived from
DataSetOptions
The Options listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class. Therefore, it inherits Options from these parent classes. If you cannot find a specific Options in this list, we recommend consulting the documentation of the DataSet.
- since
- deprecated
Properties and Attributes
The Properties and Attributes listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class and ultimately from HTMLElement. Therefore, it inherits Properties and Attributes from these parent classes. If you cannot find a specific Properties and Attributes in this list, we recommend consulting the documentation of the DataSet.
data-monster-options: Sets the configuration options for the collapse component when used as an HTML attribute.data-monster-option-[name]: Sets the value of the configuration option[name]for the collapse component when used as an HTML attribute.
Methods
The methods listed in this section are defined directly within the class. This class is derived from several parent classes, including the CustomElement class and ultimately from HTMLElement. Therefore, it inherits methods from these parent classes. If you cannot find a specific method in this list, we recommend consulting the documentation of the DataSet.
Behavioral methods
refresh()3.70.0- {Promise}
Static methods
getCSSStyleSheet()- {CSSStyleSheet[]}
getTag()- {string}
Lifecycle methods
Lifecycle methods are called by the environment and are usually not intended to be called directly.
[assembleMethodSymbol]()Other methods
reportValidity()2.10.0- {boolean}
Events
The component emits the following events:
monster-options-setmonster-selectedmonster-changemonster-changed
For more information on how to handle events, see the mdn documentation.