Skip to content

The form on your page ​

<datum-form> takes a definition and draws the form. The page around it supplies what the definition cannot know: the data behind the selects, the wording for this site, where the answers go and what the server said back. This page walks through those, with the whole thing running at the end of each part.

The whole page ​

The example is a complete page. The choices above the code rewrite it, and the result under it is that page, running.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Customer intake</title>
    <link rel="stylesheet" href="/datum/datum-form.css">
    <script type="module" src="/datum/datum-form.js"></script>
  </head>
  <body>
    <datum-form
      id="intake"
      src="/forms/customer-intake.json"
      language-switcher
    ></datum-form>

    <script type="module">
      const form = document.getElementById("intake");

      // Data sources are plain lists, keyed by the id a select names in its settings.
      form.dataSources = {
        countries: [
          { value: "CA", label: "Canada" },
          { value: "US", label: "United States" },
          { value: "MX", label: "Mexico" }
        ]
      };

      // The page's validation text per error code and language. These win over the form's own
      // messages for every code they name; the form's words stand for the codes left out.
      form.messages = {
        required: {
          default: "This field is required.",
          locales: { "fr-CA": "Ce champ est requis." }
        }
      };

      form.addEventListener("datum-submit", async ({ detail }) => {
        if (!detail.accepted) return; // the form shows its own validation errors
        try {
          const response = await fetch("/api/submissions", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ document: detail.submission, submissionKey: detail.submissionKey })
          });
          if (response.ok) {
            // The server's receipt, shown at the ends of the form that placement lists.
            const { reference } = await response.json();
            form.setNotice({
              kind: "success",
              placement: ["top"],
              title: {
                default: "Application received",
                locales: { "fr-CA": "Demande reçue" }
              },
              message: {
                default: "Keep this number for your records.",
                locales: { "fr-CA": "Conservez ce numéro pour vos dossiers." }
              },
              details: [
                {
                  label: {
                    default: "Confirmation number",
                    locales: { "fr-CA": "Numéro de confirmation" }
                  },
                  value: reference
                }
              ]
            });
            return;
          }
          // The server's verdict, back into the form: one entry per field it rejected.
          const { errors } = await response.json();
          form.setErrors(errors.map((e) => ({ componentId: e.field, code: e.code, message: e.message })));
        } catch {
          // Out of reach: an error of the form's own, listed at the top of the form.
          form.setErrors([{ code: "delivery.failed", message: "The form could not be sent. Try again." }]);
        }
      });
    </script>
  </body>
</html>
ResultThis page, running. Addresses under /forms//api/ are answered by the example.
What the page did

Nothing yet.

The definition it loads is a file of this site's: customer-intake.json.

What the page sets ​

Where the form comes from. src names a definition to fetch. A page that already holds the object assigns it to the definition property instead. Use one at a time: while one is in place the other is refused with a datum-error, so clear it first. src is a plain fetch with no headers and no credentials; for a definition behind a login, fetch it yourself and assign definition.

How it opens. locale picks the starting language from the ones the form supports, and auto takes the visitor's browser languages. language-switcher adds the form's own switcher to its header. mode="readonly" shows the answers without letting them change. frame sets the box around the form: seamless, outlined or paper. The author's own pick beats it unless frame-fixed is set.

Data sources. A select or radio group can name a source instead of listing its options. The page supplies each source under that id, as a list or as a function that returns one. See Data model and data sources.

Messages. The form's author words the validation errors in the builder. The page's messages word them too, per language, and an entry beats the author's message for the same code; a code the page leaves out keeps the author's words. In the example, submit with the name empty: the page's "This field is required." shows in place of the field's own "Enter your full name."

Drafts. With a draft key every change is saved, in the browser unless draft-store names a server. Turn on Draft autosave in the example, type a name and press Reload. See Drafts.

Taking the submission ​

A button with the action submit validates the form. If the answers pass, the form locks and raises datum-submit with detail.accepted set and the envelope, which holds the answers, in detail.submission. If they fail, the form shows its own errors and the event carries accepted: false, so a listener returns early.

The page delivers detail.signed ?? detail.submission wherever it likes. detail.submissionKey is the same for every retry of one attempt, so the server can keep one record for it. The shape of the envelope and everything else the event carries is on Submissions and replies.

Answering it ​

What the server said goes back into the form through two methods: setNotice for a receipt and setErrors for a refusal or a failed delivery. Which call fits which reply, the shape each takes, timeouts, retries and what to do after acceptance are on Submissions and replies. Both throw until the form is built; see When the form is ready.

Change Server reply in the example and submit again to see each one. Every text in a notice can be a plain string or one worded per language, as the example's receipt is.

Next ​

MIT licence. Your forms, your data, your keys.