Frequently asked questions

Get answers to commonly asked questions.

How do I run a function after form submission?

In many cases, you may want to do something after the user has submitted a form. To do this, override the onCompletion() function of the Formsmd class after instantiation. This function has the json argument, which is the result returned from hitting the postURL endpoint.

import { Composer, Formsmd } from "formsmd";

const composer = new Composer({
  id: "my-form",
  postUrl: "/api/endpoint"
});

const formsmd = new Formsmd(
  composer.template,
  document.getElementById("my-form-container"),
  {}
);

// Override to log the result
formsmd.onCompletion = function(json) {
  console.log(json);
}

formsmd.init();

How do get my server's submission errors to work?

By default, server error responses are expected to follow the OpenAPI format. However, you can customize error handling to work with your server's error format in two ways:

1. Configure the error field and message keys

If your server returns errors with different field names than the OpenAPI standard, you can configure the keys using the errorFieldKey and errorMessageKey options:

const formsmd = new Formsmd(
  composer.template,
  document.getElementById("my-form-container"),
  {
    errorFieldKey: "attr",
    errorMessageKey: "detail"
  }
);

2. Override the error parsing function

For more complex error formats, override the getSubmissionErrors() function. This function receives the JSON response from your server and should return an array of error message strings:

const formsmd = new Formsmd(
  composer.template,
  document.getElementById("my-form-container"),
  {}
);

// Override to handle errors
formsmd.getSubmissionErrors = function(json) {
  const messages = [];
  
  // Parse nested validation errors
  if (json.validation && json.validation.errors) {
    for (const error of json.validation.errors) {
      messages.push(`${error.attr}: ${error.detail}`);
    }
  }
  
  // Add general error message
  if (json.error) {
    messages.push(json.error);
  }
  
  return messages;
};

formsmd.init();

Last updated

Was this helpful?