Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Components and Helpers

Forms and Inputs

Build forms in Ember with controlled inputs, checkboxes, selects, validation and a submit flow, using tracked state and the on modifier, with runnable JavaScript stand-ins.

Forms are where most application logic lives: sign-up, search, settings, checkout. Ember gives you no special form language. You combine what you already know: tracked fields hold the values, {{on}} listens to events, getters compute validation messages, and an action performs the submit. This lesson puts those pieces together into a complete form.

Real versus stand-in. Template and component code is real Ember, read-only here. The runnable blocks model the form logic (state, validation, submit) in plain JavaScript, so you can run and change them.

A controlled text input

A controlled input means the component's state is the single source of truth; the input just displays it and reports changes.

JavaScript
// app/components/signup-form.gjs
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

export default class SignupForm extends Component {
  @tracked email = '';
  @tracked password = '';
  @tracked wantsNews = true;
  @tracked plan = 'free';

  setEmail = (event) => (this.email = event.target.value);
  setPassword = (event) => (this.password = event.target.value);
  setNews = (event) => (this.wantsNews = event.target.checked);
  setPlan = (event) => (this.plan = event.target.value);

  <template>
    <form {{on "submit" this.submit}}>
      <label>Email <input type="email" value={{this.email}} {{on "input" this.setEmail}} /></label>
      <label>Password <input type="password" value={{this.password}} {{on "input" this.setPassword}} /></label>
      <label>
        <input type="checkbox" checked={{this.wantsNews}} {{on "change" this.setNews}} />
        Send me news
      </label>
      <select {{on "change" this.setPlan}}>
        <option value="free" selected={{eq this.plan "free"}}>Free</option>
        <option value="pro" selected={{eq this.plan "pro"}}>Pro</option>
      </select>
      <button type="submit">Create account</button>
    </form>
  </template>
}

Details worth knowing:

  • Text inputs use the input event so every keystroke updates state. Checkboxes and selects use change.
  • Checkboxes read event.target.checked, everything else event.target.value.
  • Use checked={{...}}, value={{...}} and selected={{...}} to bind properties, not attributes; these update the live control.
  • eq comes from ember-truth-helpers (or compare in a getter).

Repeating four near-identical setters gets old. A small helper reduces it:

JavaScript
setField = (name) => (event) => {
  const el = event.target;
  this[name] = el.type === 'checkbox' ? el.checked : el.value;
};
// in the template: {{on "input" (this.setField "email")}}

That is a function returning a function, so the template never needs inline code.

The built-in Input component

Ember also ships <Input> and <Textarea>, which two-way bind to a value:

JavaScript
import { Input } from '@ember/component';

<template>
  <Input @type="text" @value={{this.title}} placeholder="Title" />
</template>

@value={{this.title}} writes back into this.title when the user types. That implicit write is convenient but hides data flow, which is why many teams choose plain <input> plus {{on}}. Either works; use one consistently.

Validation with getters

Validation is derived state, so write it as getters:

JavaScript
get emailError() {
  if (!this.touched) return null;
  if (!this.email.includes('@')) return 'Enter a valid email address.';
  return null;
}

get passwordError() {
  return this.password.length < 8 ? 'Use at least 8 characters.' : null;
}

get isValid() {
  return !this.emailError && !this.passwordError;
}
JavaScript
<template>
  {{#if this.emailError}}
    <p class="error" role="alert">{{this.emailError}}</p>
  {{/if}}
  <button type="submit" disabled={{this.isInvalid}}>Create account</button>
</template>

Show errors only after the user has interacted (a touched flag) or tried to submit, otherwise the form scolds people before they type. Keep messages next to their field and link them with aria-describedby; that makes them accessible to screen readers.

JS Stand-in: a form with validation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The submit flow

A realistic submit action has states: idle, saving, saved, failed.

JavaScript
@tracked status = 'idle';
@tracked errorMessage = null;

submit = async (event) => {
  event.preventDefault();
  this.touched = true;
  if (!this.isValid) return;

  this.status = 'saving';
  try {
    await this.args.onSubmit({ email: this.email, password: this.password });
    this.status = 'saved';
  } catch (error) {
    this.errorMessage = error.message;
    this.status = 'failed';
  }
};
JavaScript
<button type="submit" disabled={{eq this.status "saving"}}>
  {{if (eq this.status "saving") "Saving..." "Create account"}}
</button>

Disabling the button while saving prevents double submits. Network calls usually live in a service or through the store, and the component only calls them (see Services in Ember). Rendering after await is safe: assigning tracked fields after the component has been destroyed is harmless in current Ember, but you can guard with if (this.isDestroying || this.isDestroyed) return; when you want to be strict.

JS Stand-in: async submit states

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Forms bound to a model

When you edit an Ember Data record, avoid binding inputs straight to it; typing would change the record (and every screen showing it) before the user presses Save. Instead copy the values into the form's own tracked fields, or use a changeset (the ember-changeset add-on), then write to the record on submit. The record lessons in Ember Data: Models and the Store show how saving works.

Resetting and cancelling

JavaScript
reset = () => {
  this.email = '';
  this.password = '';
  this.touched = false;
  this.status = 'idle';
};

For a "Cancel" button, either call reset or let the parent hide the component; a hidden component throws its state away automatically.

Accessibility checklist

  • Every control has a visible <label> (wrap it, or link with for and id; {{unique-id}} generates safe ids).
  • Errors use role="alert" or aria-live and are tied with aria-describedby.
  • Use the right type (email, tel, number) so mobile keyboards adapt.
  • The submit button is a real <button type="submit">, so Enter works.

Common mistakes

  • Using onclick on the submit button instead of submit on the form. Enter key submits would bypass your logic.
  • Binding to a model directly. Edits leak into the app before saving.
  • Mutating arrays in tracked state. Replace instead (see Reactivity Pitfalls).
  • No error handling in async submit. A rejected promise leaves the button stuck.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event keeps a text input's tracked field updated on every keystroke?

    input fires for each edit. change fires when the control loses focus (or is toggled, for checkboxes and selects).
  2. 2. How do you read the state of a checkbox?

    A checkbox's boolean state is on the checked property of the element.
  3. 3. Why should validation messages be getters?

    Derived values should not be stored; a getter reads tracked fields, so the template updates when they change.
  4. 4. Why not bind inputs directly to an Ember Data record being edited?

    Edit a copy in the form's own state, or use a changeset, and write to the record only on submit.

Summary

  • Keep form values in @tracked fields; update them from input and change events.
  • Checkboxes use checked, selects and text inputs use value.
  • Validation is derived state: write getters, and show errors after interaction.
  • Model the submit as states (idle, saving, saved, failed) and disable the button while saving.
  • Edit a copy of record data, not the record itself, until the user saves.

Next: Ember Data: Models and the Store