JavaScript SDK
This page describes the Form.io JavaScript SDK
The JavaScript API is a minimalistic API library that allows you to work with the Form.io API's within your web application.
The Form.io SDK is part of our Open Source formio.js library which is found @ https://github.com/formio/formio.js. There are two ways to include the JavaScript SDK into your application.
You can include it in a script tag within your application like the following shows.
<script src="https://cdn.form.io/formiojs/formio.min.js"></script>
Which would would then be able to do the following within your application.
<script type="text/javascript">
// Load a form.
var formio = new Formio('https://myproject.form.io/myform');
formio.loadForm().then(function(form) {
console.log(form);
});
</script>
You can also import the SDK into your application as follows.
First perform an
npm install
using the terminal application.npm install --save formiojs
Then, you can import it into your application as follows.
import Formio from 'formiojs/Formio';
// Load a form
const formio = new Formio('https://myproject.form.io/myform');
formio.loadForm().then(function(formio) {
console.log(formio);
});
Creating an instance of Formio is simple, and takes only a path (URL String). The path can be different, depending on the desired output. The Formio instance can also access higher level operations, depending on how granular of a path you start with.
const formio = new Formio(<endpoint>, [options]);
Where endpoint is any valid API endpoint within Form.io. These URL's can provide a number of different methods depending on the granularity of the endpoint. This allows you to use the same interface but have access to different methods depending on how granular the endpoint url is.
The options (optional) is used to configure certain behaviors of the JavaScript API. The following options are available.
Property | Description | Example |
base | Allows you to override the base api url. | |
project | Allows you to override the project api url. | |
namespace | The namespace to store the localStorage variables. Defaults to formio | formio |
When using the JavaScript SDK, it is important to understand the different kinds of API scopes that are being queried via the API. The Form.io API is hierarchical which is also congruent with the JavaScript SDK when making API calls with the SDK. The following scopes are provided via the Form.io API / SDK (we will use "formio.com" as the hypothetical domain name you have deployed the Form.io platform against.
Scope | Description | Example API |
Root | This is the root or base URL for your Form.io deployment | https://formio.com |
Project | This is the API endpoint for a specific project | :rootScope/project/:projectId |
Form | This is the API endpoint for a specific | :projectScope/form/:formId |
Submission | This is the API endpoints for a specific submission | :formScope/submission/:submissionId |
Action | This is the API endpoints for specific action | :formScope/action/:actionId |
Role | This is the API endpoints for a specific role. | :projectScope/role/:roleId |
The Form.io API also uses aliases to make the use of the hierarchical API's easier to use. Currently, we provide alias support for both Projects and Forms, so that a typical Form URL would look like the following.
https://formio.com/myproject/myform
Where "formio.com" would be replaced with the URL of your deployment, "myproject" would be replaced with the alias name of your project, and "myform" would be replaced with the name of your form. All API endpoints within the examples below will use this URL format to demonstrate the different kinds of SDK methods.
If you wish to load the project JSON, or search for forms, you will instantiate as follows.
const formio = new Formio('https://formio.com/myproject');
formio.loadForms().then((forms) => {
console.log(forms);
});
If you wish to load a specific submission.
const formio = new Formio('https://formio.com/myproject/myform/submission/23234234234234');
formio.loadSubmission().then((submission) => {
console.log(submission);
});
Now that we understand how the SDK works, we can see all of the different API's available to the different API scopes as follows.
There are a few methods that are used statically, meaning that they do not require the
new Formio
as the other methods require. These methods can be used as globals that are able to define the behavior of the JavaScript SDK and all instances created afterward. These methods are as follows.Sets the Base URL of the renderer and SDK. This is a very important method that allows you to provide to the JavaScript SDK the Base Deployment URL of your API platform. This is always going to be the root URL of your deployment, which is also the same as the URL for the deployed developer portal application (if you have that enabled). The best way to know if you have this correct is that you should see the "status" of your deployment by going to
:baseUrl/status
If this shows the version of the server, then you know this is the value of the base URL.Example:
Formio.setBaseUrl('https://forms.yoursite.com');
This is the Project URL that will be used to reference any Project endpoints within the SDK and renderer. This is also important to establish within your application to ensure that all relative urls are referencing the correct Project endpoints.
Example:
Formio.setProjectUrl('https://forms.yoursite.com/yourproject');
A static method to perform an API request to any REST API endpoint. This method is a simple wrapper around the JavaScript fetch method with the added handling of JWT tokens as well as implements a Caching mechanism for GET requests to ensure that multiple requests of the same nature do not constantly spam the API server. It's parameters are defined as follows.
Parameter | Description |
url | The URL you wish to send the request to. |
method (optional) | The method of the request. GET, PUT, POST, DELETE |
data (optional) | The data to include for PUT and POST requests |
header (optional) | An instance of the HTTP Header class to define headers for this request. |
opts (optional) |
Example: Send a request to fetch submissions.
Formio.request(
'https://examples.form.io/customers/submission?data.number=1',
'GET',
null,
null,
{
headers: {
'content-type': 'application/json'
},
mode: 'cors',
}).then(function(result) {
console.log(result);
});
This static method performs an API call to the Form.io API platform. This method is very similar to other request method but will also send the request through the Form.io fetch plugin to allow any fetch plugin to intercept the request being made. Its parameters are defined as follows.
Parameter | Description |
url | The URL you wish to send the request to. |
method (optional) | The method of the request. GET, PUT, POST, DELETE |
data (optional) | The data to include for PUT and POST requests |
opts (optional) |
Sets or removes the JWT token within localStorage.
Parmeter | Description |
token | A JWT token to set within localStorage. If the value of this parameter is empty, then the token will be deleted from localStorage. |
Retrieve the JWT token from localStorage.
Sets the User JSON object of the currently logged in user. This is the same JSON object that you would get if you sent an API request to
/current
with your current JWT token. This user object is then stored within localStorage as formioUser
unless a different namespace
option is being used.Parameter | Description |
user | The JSON of the user object that is fetched from the /current endpoint. |
Fetch the user JSON object from the localStorage.
Fetch the current user via the
/current
API endpoint.Parameter | Description |
formio (optional) | An instance of the Formio SDK if necessary. |
opts (optional) |
Retrieves the access information for a specific project. You must ensure you set the project url using
Formio.setProjectUrl()
before calling this method.Parameter | Description |
formio (optional) | An instance of the Formio SDK if necessary. |
Retrieves the roles for a specific project. You must ensure you set the project url using
Formio.setProjectUrl()
before calling this method.Parameter | Description |
formio (optional) | An instance of the Formio SDK if necessary. |
Clears all the fetch caches to ensure that any future requests will retrieve fresh data from the API's.
Perform a logout against the Form.io API server.
Helper function to retrieve all of the URL query parameters in a javascript key-value pair mapped object.
Example: Given the following url
https://yourapp.formio.com/#/home?data.firstName=Travis&sort=-created
If you run this method on that page, it will return the following.
const pageQuery = Formio.pageQuery();
console.log(pageQuery['data.firstName']); // Prints "Travis"
console.log(pageQuery.sort); // Prints "-created"
Initializes an SSO processes. This is used during SAML authentication processes to instantiate and continue a SAML SSO process.
Assuming that your project is configured for SAML, you can instantiate an SSO process by executing the following.
Formio.ssoInit('saml')
Once the SAML authentication returns to the application, you can process that response using the following.
if (Formio.pageQuery().saml) {
const sso = Formio.ssoInit('saml');
if (sso) {
sso.then((user) => {
window.location.href = '/';
});
}
}
The following parameters can be used.
Parameter | Description |
type | The type of SAML sso authentication to instantiate. Either "saml" or "okta" |
options | An object of options, which depends on the type. For saml type: - relay: This is the variable that will be provided to the relay of the sso process. For okta type: - OktaAuth: An instance of the OktaAuth javascript object provided by Okta Javascript SDK - formio: An instance of the Form.io SDK. - scopes: A string of CSV scopes to apply |
Require an external JavaScript library for lazy-loading purposes.
Parameter | Description |
name | The name of the library |
property | The property that is added to the "window" object that indicates that the library has finished loading. For example, if you are wanting to load the "Lodash" library, the variable that is added to the window object is "_" |
src | The URL of the library you wish to load. |
polling | Creates a polling check to see if the library has finished loading. |
Formio.requireLibrary(
'lodash',
'_',
'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js',
true
).then(function() {
console.log(_.version); // Lodash is now part of the dom.
});
Returns a promise that will resolve once the library of the provided name is ready to be used.
Parameter | Description |
name | The name of the library to check if it is ready or not. |
Formio.libraryReady('lodash').then((_) => {
// Lodash is now ready!
console.log(_);
});
A static method to load all projects within the configured
baseUrl
of the SDK.Parameter | Description |
query (optional) | |
opts (optional) |
A method that will serialize a data map key-value pair object into a URL query string.
Parameter | Description |
obj | The object to serialize into a URL query string. |
interpolate (optional) | An optional interpolation method to interpolate certain values that are added. |
The following API's are defined at the Project Scope. To instantiate the SDK at the project scope, you simply need to provide a Project API to the constructor as follows.
const formio = new Formio('https://forms.formio.com/myproject')
where "myproject" would be the alias name of your project. Once you have instantiated the SDK with the following URL, the following methods are now available to you at the Project Scope.
Loads the project using the following Project Load API
Parameter | Description |
query (optional) | |
opts (optional) |
formio.loadProject().then((project) => {
// Prints the project JSON
console.log(project);
});
Creates or Updates a project depending on if the _id of the project is provided (upsert).
Example: Create a new project
const formio = new Formio('https://api.form.io');
formio.saveProject({
"title": "New Project",
"name": "proj980",
"description": "An example application",
"settings": {
"cors": "*"
}
}).then((project) => {
// Prints the project that was saved via API.
console.log(project);
});
Example: Update an existing project.
const formio = new Formio('https://forms.formio.com/myproject');
formio.loadProject().then((project) => {
project.title = 'Updated Title';
formio.saveProject(project).then((updated) => {
// Prints the updated project json.
console.log(updated);
});
});
Parmameters | Description |
project | The project JSON you wish to create or update. If an "_id" is provided within the json, an update operation will be executed, otherwise it will create a new project. |
opts (optional) |
Deletes a project.
var formio = new Formio('https://myproject.form.io');
formio.deleteProject().then(() => {
console.log('The project has been deleted!');
});
Parmameters | Description |
opts (optional) |
Parameter | Description |
query (optional) | |
opts (optional) |
Example: List all Resources within a project, sort them based on created date, and only return the "title" and "path" of those forms
formio.loadForms({
params: {
type: 'resource',
select: 'title,path',
sort: '-created'
}
}).then((resources) => {
console.log(resources);
});
Example: List all Forms within a project, limit them to 20, and only return the "title" of those forms.
formio.loadForms({
params: {
type: 'form',
select: 'title',
limit: 20
}
}).then((forms) => {
console.log(forms);
});
Retrieves a temporary auth token which can be used in conjunction with the PDF API's to download a PDF output of a submission.
formio.getTempToken(
3600,
'GET:/project/234234234234234/form/234234234234234/submission/234234234234234/download'
).then((tokens) => {
console.log(tokens);
});
Parameter | Description |
opts (optional) |
Returns the Project ID of the project in context, even if the URL provided to the constructor uses the project alias.
const formio = new Formio('https://forms.formio.com/myproject');
formio.getProjectId().then((projectId) => {
// Prints the project id for the "myproject" project.
console.log(projectId);
});
formio.accessInfo().then((accessInfo) => {
// Output the role information for this project.
console.log(accessInfo.roles);
});
Based on the JWT token stored within the localStorage, this method will retrieve the current user metadata and information.
formio.currentUser().then((user) => {
// The current user.
console.log(user);
});
The following API's are available when the Form.io SDK is instantiated with the form scope like the following illustrates
const formio = new Formio('https://forms.formio.com/myproject/myform');
Loads a form json
Parameter | Description |
query (optional) | |
opts (optional) |
Creates or Updates a form depending on if an "_id" property is provided within the form json.
Parameter | Description |
form | The JSON of the form to save or update. If an "_id" is provided as a property of the form json, then an update operation is performed, otherwise, it will create a new form. |
opts (optional) |
Example: Create a new form
// Project scope is only required for creating new forms.
const formio = new Formio('https://forms.formio.com/myproject');
formio.saveForm({
title: 'Registration',
path: 'registration',
name: 'registration',
components: [
{type: 'textfield', key: 'firstName', label: 'First Name'}
{type: 'textfield', key: 'lastName', label: 'Last Name'}
]
}).then((form) => {
// Prints out the saved form object.
console.log(form);
});
Example: Update an existing form
const formio = new Formio('https://forms.formio.com/myproject/myform');
formio.loadForm().then((form) => {
form.title = 'Updated title';
formio.saveForm(form).then((updated) => {
console.log(updated);
});
});
Deletes a form
Property | Description |
opts (optional) |
const formio = new Formio('https://forms.formio.com/myproject/myform');
formio.deleteForm().then(() => {
console.log('Form was deleted!');
});
Returns the form Id of the form in context even if the form alias was provided for this form.
const formio = new Formio('https://forms.formio.com/myproject/myform');
formio.getFormId().then((formId) => {
// Prints the form id for "myform"
console.log(formId);
});
Parameter | Description |
query (optional) | |
opts (optional) |
Example: Load first 10 submissions, sort by descending created date
formio.loadSubmissions({
params: {
sort: '-created'
}
}).then((submissions) => {
console.log(submissions);
});
Example 2: Load first 20 submissions where the form field age is greater than 18, and sort by modified.
formio.loadSubmissions({
params: {
sorted: 'modified',
'data.age__gt': 18,
limit: 20
}
}).then((submissions) => {
console.log(submissions);
});
Parameter | Description |
query (optional) | |
opts (optional) |
Examples will be very similar to the loadSubmissions API, but will query against the action json objects instead.
Returns a list of available actions that can be added to this form. Implements the Available Actions API.
Returns the action information for a specific action including the settings form. This implements the Action Info API
Parameter | Description |
name | The name of the action you would like to retrieve information on. |
The following API's are available when the Form.io SDK is instantiated with the submission scope like the following illustrates
const formio = new Formio('https://forms.formio.com/myproject/myform/submission/234234234234234');
Loads a submission for a given form.
Parameter | Description |
query (optional) | |
opts (optional) |
Example: Load the submission
const formio = new Formio('https://forms.formio.com/myproject/myform/submission/234234234234234');
formio.loadSubmission().then((submission) => {
console.log(submission);
});
Creates or Updates a submission depending on if an "_id" property is provided within the submission json.
Parameter | Description |
submission | The JSON of the submission to save or update. If an "_id" is provided as a property of the submission json, then an update operation is performed, otherwise, it will create a new submission. |
opts (optional) |
Example: Create a new submission
// Form scope is only required for creating new submissions.
const formio = new Formio('https://forms.formio.com/myproject/myform');
formio.saveSubmission({
data: {
firstName: 'Joe',
lastName: 'Smith'
}
}).then((submission) => {
// Prints out the saved submission object.
console.log(submission);
});
Example: Update an existing submission
const formio = new Formio('https://forms.formio.com/myproject/myform/submission/234234234234234');
formio.loadSubmission().then((submission) => {
submission.data.firstName = 'Updated Name';
formio.saveSubmission(submission).then((updated) => {
console.log(updated);
});
});
Deletes a submission
Property | Description |
opts (optional) |
const formio = new Formio('https://forms.formio.com/myproject/myform/submission/234234234234234');
formio.deleteSubmission().then(() => {
console.log('Submission was deleted!');
});
Retrieves a PDF download url for a specific form.
Parameter | Description |
form | The form JSON to retrieve a download url from. If none is provided, then it will use the form that is in scope. |
const formio = new Formio('https://forms.formio.com/myproject/myform/submission/234234234234234');
formio.getDownloadUrl().then((url) => {
// This will print the PDF download url, which also includes the temp token.
console.log(url);
});
Uploads a file to the provided storage system. See File Component for specific usage and implementation details.
Downloads a file from the provided storage system. See File Component for specific usage and implementation details.
Deletes a file from the provided storage system. See File Component for specific usage and implementation details
The following API's are available when the Form.io SDK is instantiated with the action scope like the following illustrates