universal-ember / dev

Documentation for platform-powered modern single page apps
0 stars 0 forks source link

Controlled Forms #2

Open NullVoxPopuli opened 8 months ago

NullVoxPopuli commented 8 months ago

Controlled Forms

This type of form is handled by and built with this styleless Forms implementation. The library provides provides a way to build your fields, which we will use with the unique, non-native fields provided by ember-primitives

[ember-headless-form] distills the common behavior and accessibility best practices of forms into reusable components, without any opinions on specific markup or styling. Use it to build your forms directly, or to build your opinionated forms component kit on top of it. from the docs

The Light Form does not provide any accessibility guidance between labels, inputs, errors, and other statuses (because the light form is just a <form> element). ember-headless-form solves all of this boilerplate for you.

NullVoxPopuli commented 8 months ago

Switch

Here is an example of how to integrate <Switch /> with <HeadlessForm />, using Bootstrap for styling.

import { HeadlessForm } from 'ember-headless-form';
import { Switch } from 'ember-primitives';
import { cell } from 'ember-resources';
import { on } from '@ember/modifier';
import { fn } from '@ember/helper';

const data = cell({ stayLoggedIn: false });

function handleSubmit(submittedData) {
  data.current = { ...submittedData }; 
}

function handleChange(set, event) {
  set(event.target.checked);
}

<template>
  <HeadlessForm @data={{data.current}} @onSubmit={{handleSubmit}} as |form|>
    <form.Field @name='stayLoggedIn' as |field|>
      <Switch class="form-check form-switch" as |s|>
        <s.Control 
          class="form-check-input" 
          id={{field.id}}
          name="stayLoggedIn"
          checked={{field.value}}
          {{on 'change' (fn handleChange field.setValue)}} 
        />
        <field.Label class="form-check-label">
          Stay Logged In
        </field.Label>
      </Switch>
    </form.Field>

    <button type='submit' class="btn btn-primary">Submit</button>
  </HeadlessForm>

  <br />Submitted form data:
  <pre>{{JSON.stringify data.current null 3}}</pre>

  {{!-- Using Bootstrap styles --}}
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</template>