Loading form definitions
The builder stores the complete form structure in a single JavaScript object called the form definition. It includes all the properties and settings of the elements used in the form. Loading a form is as simple as feeding a form definition to the builder. This guide shows you how to do that.
▶️ Start the builder with a form
To start a new builder instance with a form, use the static open
method to create a new builder instance and supply the form that needs to be loaded right away.
import { Builder } from "@tripetto/builder";
// Open the builder with the form
Builder.open(/* Supply your form definition here */);
// You can use the second parameter to configure the builder
Builder.open(/* Supply your form definition here */, {
onChange: (definition) => {
console.log("A change was made!");
console.dir(definition);
}
});
📂 Loading a form
When you have a builder instance, you can call the load
method to load another form. You can also use the definition
property and set it to another form. The result is the same, the current form gets cleared and the supplied form loaded.
import { Builder } from "@tripetto/builder";
// Create a new builder instance
const builder = new Builder();
// Open the builder
builder.open();
// Load a form
builder.load(/* Supply your form definition here */);
// Or use the definition property
builder.definition = /* Supply your form definition here */;
👩💻 Simple AJAX example
The actual loading (fetching) of a form definition from a data store is entirely up to you. You could, for example, use an AJAX call to fetch a form from a server and then supply it to the builder.
- fetch()
- XMLHttpRequest
- SuperAgent
- Axios
import { Builder } from "@tripetto/builder";
const response = await fetch("/example-form.json");
const form = await response.json();
Builder.open(form);
import { Builder } from "@tripetto/builder";
const httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
Builder.open(JSON.parse(httpRequest.responseText));
}
};
httpRequest.open("GET", "/example-form.json");
httpRequest.send();
import { Builder } from "@tripetto/builder";
import { get } from "superagent";
get("/example-form.json")
.send()
.then((response: Superagent.Response) => {
if (response.ok) {
Builder.open(response.body);
}
});
import { Builder } from "@tripetto/builder";
import { get } from "axios";
get("/example-form.json")
.then((response) => {
Builder.open(response.data);
});