# Submit

> Validate, save, and show how the save went.

Source: https://forms.lunarhue.dev/solid/basics/submit

`onSubmit` on the definition runs when the user submits a valid form. What
it returns is the submission's result, and it may be async. The form's state
tracks the submit while it runs. Try `taken@example.com` in the demo.

```tsx title="account.tsx"
import { createForm, createForms, useFormContext } from "@lunarhue/forms-solid";
import { Show } from "solid-js";
import { saveAccount } from "./server";
import { TextInput } from "./TextInput";

const forms = createForms();

const account = forms.define({
  defaultValues: { name: "", email: "" },
  validate: {
    fields: {
      name: (name) => (name === "" ? { message: "Enter your name." } : undefined),
      email: (email) => (email.includes("@") ? undefined : { message: "Enter a valid email." }),
    },
  },
  // Runs only once the value is valid. What it returns is the result.
  onSubmit: async (value, { store }) => {
    const response = await saveAccount(value);
    if (!response.ok) {
      // The server said no: show why on the field.
      store.setErrors({ fields: { email: { message: response.error } } });
      return null;
    }
    return `Saved ${value.name}.`;
  },
});

// `form.state` is reactive, so only these two spots update.
function SubmitButton() {
  const form = useFormContext(forms);
  return (
    <button type="submit" disabled={form.state.submitting}>
      {form.state.submitting ? "Saving..." : "Save"}
    </button>
  );
}

export default function AccountForm() {
  const form = createForm(account, { id: "account" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.Field name="name">{(field) => <TextInput field={field} label="Name" />}</form.Field>
          <form.Field name="email">{(field) => <TextInput field={field} label="Email" type="email" />}</form.Field>
          <SubmitButton />
          <p role="status">
            <Show when={form.state.submission.status === "succeeded" && form.state.submission}>
              {(submission) => submission().result}
            </Show>
          </p>
        </form>
      )}
    </form.Form>
  );
}
```

```ts title="server.ts"
// A pretend server: it takes a moment and refuses one email.
export async function saveAccount(value: { name: string; email: string }) {
  await new Promise((resolve) => setTimeout(resolve, 800));
  if (value.email === "taken@example.com") return { ok: false as const, error: "That email is taken." };
  return { ok: true as const };
}
```

```tsx title="TextInput.tsx"
import { type FieldApi, inputProps } from "@lunarhue/forms-solid";
import { For } from "solid-js";

interface TextInputProps {
  readonly field: FieldApi<string>;
  readonly label: string;
  readonly type?: "text" | "email" | "password";
}

// A plain component that takes the field `form.Field` hands its child.
// Read it through `props`: destructuring stops it updating.
export function TextInput(props: TextInputProps) {
  return (
    <div>
      <label for={props.field.id}>{props.label}</label>
      <input {...inputProps(props.field, { type: props.type ?? "text" })} />
      <ul id={props.field.errorId}>
        <For each={props.field.shownErrors}>{(error) => <li>{error.message}</li>}</For>
      </ul>
    </div>
  );
}
```

## onSubmit

```ts
const account = forms.define({
  defaultValues: { name: "", email: "" },
  onSubmit: async (value, { store, signal }) => {
    const response = await fetch("/api/account", {
      method: "PUT",
      body: JSON.stringify(value),
      signal,
    });
    return response.json();
  },
});
```

`value` is a copy of the form's value, which you may change without touching
the form. With a [schema](https://forms.lunarhue.dev/solid/basics/schema-validation.md) it is the schema's output.
The second argument has:

- `store`, the form's store, for `setErrors` and the rest.
- `signal`, which aborts when the form is reset while the submit runs.
- `intent`, the value passed to `form.submit(intent)`. See [Intents](#intents).
- `input`, the form value that passed validation, before the schema
  transformed it.

## What a submit does

Spreading `formProps` on the `<form>` element wires its submit event to
`form.handleSubmit`. A submit then:

1. Clears the errors the last submit set with `setErrors`, counts the
   submit, and sets the status to `"submitting"`.
2. Runs validation, and waits for async validators to finish.
3. Stops with status `"invalid"` if any field has an error, and moves focus
   to the first invalid field. `onSubmit` isn't called.
4. Otherwise calls `onSubmit`. Its return value ends the submit as
   `"succeeded"`, and a throw as `"failed"`.

A submit while one is running doesn't start another. It returns the running
one.

To submit from code, call `form.submit()`. It resolves to the submission.
Turn off the focus move with `focusOnInvalid: false` on `createForms`, or
pass a function to handle it yourself.

## Submit state

The form snapshot has the state of the latest submit:

| Member | What it is |
| --- | --- |
| `submitting` | True while a submit runs. |
| `submission` | `{ status }`: `"idle"`, `"submitting"`, `"invalid"`, `"succeeded"` with `result`, or `"failed"` with `error`. |
| `submitCount` | How many submits have started, including invalid ones. |
| `valid`, `validating` | No validation errors, a validator running. |

Read it from `form.state`. Its members are reactive, so
`form.state.submitting` in JSX updates only that spot:

```tsx
<button type="submit" disabled={form.state.submitting}>
  Save
</button>
```

A component under `form.Form` gets the form from `useFormContext(forms)`,
so a submit button needs no props.

## When the server says no

A server that refuses the save usually says why. Put that on the form with
`store.setErrors` and return:

```ts
onSubmit: async (value, { store }) => {
  const response = await saveAccount(value);
  if (!response.ok) {
    store.setErrors({
      form: { message: "Nothing was saved." },
      fields: { email: { message: "That email is taken." } },
    });
    return null;
  }
  return `Saved ${value.name}.`;
},
```

`fields` is keyed by field name. `form` errors land on the form's root
field, so render the root's errors somewhere, or the user sees nothing. See
[`submit:unseen`](https://forms.lunarhue.dev/errors.md#core:submit:unseen) for how.

A name that matches no field also lands on the root, after the `form`
errors, and development warns with
[`field:unknown`](https://forms.lunarhue.dev/errors.md#core:field:unknown). That happens when the server
renames a field before the form catches up. A name counts as a field when the
value has that key, when a field there is rendered or validated, or when it
sits under an object that is missing. To send such errors somewhere else,
such as a toast, check each name with `store.pathOf` first:

```ts
// The names to show in a toast instead.
const unknown = Object.keys(response.fields).filter((name) => store.pathOf(name) === undefined);
```

Errors set this way don't block the next submit. Each one clears when the
user edits its field, and they all clear when the next submit starts.

## Error summary

A long form can list its errors at the top, so the user sees what the server
refused without scrolling. Each entry has the field's `name`, its `errors`,
and its handle as `field`, whose `id` is the input's id. The root comes first
with name `""`, and the rest follow in form order. The list counts errors from
validation and from `setErrors` alike.

```tsx
function Summary() {
  const form = useFormContext(forms);
  const invalid = createInvalidFields(form);
  return (
    <ul>
      <For each={invalid()}>
        {(entry) => (
          <li>
            <a href={`#${entry.field.id}`}>{entry.name || "Form"}</a>:{" "}
            {entry.errors.map((error) => error.message).join(" ")}
          </li>
        )}
      </For>
    </ul>
  );
}
```

A submit that validation stops moves focus to the first invalid field. One
that `onSubmit` ends with `setErrors` doesn't, since the submit itself
succeeded. To focus the first field the server refused, call
`store.firstInvalid()` after the submit resolves:

```ts
await form.submit();
const field = form.store.firstInvalid();
if (field) document.getElementById(field.id)?.focus();
```

A plugin can refuse a submit too. Its `onSubmit` hook returns `refuse`, and
the submit ends `"invalid"` without calling yours. See
[Writing a plugin](https://forms.lunarhue.dev/solid/writing-plugins/first-plugin.md).

## Intents

A form with two submit buttons, such as Save draft and Publish, can pass an
intent. Annotate `ctx.intent` to type it:

```ts
const post = forms.define({
  defaultValues: { title: "", body: "" },
  onSubmit: (value, ctx: { intent: "draft" | "publish" }) => save(value, ctx.intent),
});
```

Then call `form.submit("draft")` or `form.submit("publish")` from each
button's click. `submit()` with no intent is now a type error, and the
`<form>`'s own submit event submits with an `undefined` intent.
