Kin Form
Docs
INTRODUCTION
Getting Started Architecture

EXAMPLES
Basic Example Any-level Validation Dependent Field Validation Flexible Form Structures Flexible Field Components Array

API

Array

This example demonstrates array field and array operations.
It also demonstrates the use of custom valueFormatter and valueParser on the unit price fields.

Key Concepts

This example demonstrates how to manage a dynamic list of fields, a common requirement for things like order forms or editable invoices.

  1. Binding to Array Items: The field() directive can bind to a specific item in an array using dot notation with an index (e.g., items.0.productId). In the example, we use Lit's repeat directive to loop through the items array and generate a row for each item, using the index idx to create the correct binding for each field.

    ${repeat(value.items, (_, idx) => idx, this.#itemTemplate)}
    
    // Inside the item template
    html`<select-field ${form.field(`items.${idx}.productId`)}></select-field>`
    
  2. Array Manipulation API: The FormController (which is a FieldGroup) provides methods for manipulating arrays in the form's value. You call the method with the path to the array and the necessary arguments.

    • pushItem("items", ...): Adds a new item to the end of the items array.
    • removeItem("items", idx): Removes the item at the specified idx.
    • moveItem("items", idx, newIdx): Moves an item from one index to another.

    These methods automatically update the form state, triggering a re-render of the repeat directive.

  3. Custom Formatting and Parsing: The "Unit Price" field uses a valueFormatter to display the number as a currency string (e.g., "$10.00") and a valueParser to convert the string back into a number when the user changes it. This is useful for handling data that has a different representation in the UI versus the data model.

    <number-field
      .valueParser=${parseCurrency}
      .valueFormatter=${formatCurrency}
      ${form.field(`items.${idx}.unitPrice`)}
    ></number-field>
    
  4. Derived State with @lit/task: The total price is calculated using @lit/task. The task is configured to re-run its calculation whenever the items array changes, providing a clean and reactive way to display computed values.

Live Demo

On this page

Key Concepts Live Demo
Created with ♥️ by  Man Hoang (Kin)