Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controlled Forms #2

Open
NullVoxPopuli opened this issue Nov 11, 2023 · 1 comment
Open

Controlled Forms #2

NullVoxPopuli opened this issue Nov 11, 2023 · 1 comment

Comments

@NullVoxPopuli
Copy link

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
Copy link
Author

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant