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.

Installation

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.

Include using script tag

You can include it in a script tag within your application like the following shows.

<script src="https://cdn.form.io/js/formio.full.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>

Import into application

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);
});

Usage

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

API Scopes

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

Project and Form Aliases

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.

Examples

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.

Static Methods

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.

Formio.setBaseUrl(baseUrl)

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');

Formio.setProjectUrl(projectUrl)

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');

Formio.fetch(...)

This method is a simple shim around the HTTP Fetch polyfill.

Formio.request(url, [method], [data], [header], [opts])

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);
  });

Formio.makeStaticRequest(url, [method], [data], [opts])

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)

Formio.setToken(token)

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.

Formio.getToken()

Retrieve the JWT token from localStorage.

Formio.setUser(user)

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.

Formio.getUser()

Fetch the user JSON object from the localStorage.

Formio.currentUser([formio], [opts])

Fetch the current user via the /current API endpoint.

Parameter

Description

formio (optional)

An instance of the Formio SDK if necessary.

opts (optional)

Formio.accessInfo([formio])

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.

Formio.projectRoles([formio])

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.

Formio.clearCache()

Clears all the fetch caches to ensure that any future requests will retrieve fresh data from the API's.

Formio.logout([formio], [opts])

Perform a logout against the Form.io API server.

Formio.pageQuery()

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"

Formio.ssoInit([type], [options])

Initializes an SSO processes. This is used during SAML authentication processes to instantiate and continue a SAML SSO process.

Instantiate 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')

Process a SAML response

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

Formio.requireLibrary(name, property, src, [polling])

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.
});

Formio.libraryReady(name)

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(_);
});

Formio.loadProjects([query], [opts])

A static method to load all projects within the configured baseUrl of the SDK.

Parameter

Description

query (optional)

opts (optional)

Formio.serialize(obj, [interpolate])

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.

Project API Scope

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.

formio.loadProject([query], [opts])

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);
});

formio.saveProject(project, [opts])

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)

formio.deleteProject([opts])

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)

formio.loadForms([query], [opts])

Loads all the forms within a project. This implements the List Forms API.

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);
});

formio.getTempToken(expire, allowed, [options])

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);
});

formio.loadRoles([opts])

Loads a list of roles for the provided project. Implements the List Roles API

Parameter

Description

opts (optional)

formio.getProjectId()

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()

Retrieve the access information for a project. This method implements the Project Access Info API

formio.accessInfo().then((accessInfo) => {
    // Output the role information for this project.
    console.log(accessInfo.roles);
});

formio.currentUser()

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);
});

Form API Scope

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');

formio.loadForm([query], [opts])

Loads a form json

Parameter

Description

query (optional)

opts (optional)

formio.saveForm(form, [opts])

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);
  });
});

formio.deleteForm([opts])

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!');
});

formio.getFormId()

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);
});

formio.loadSubmissions([query], [opts])

Loads a view of submissions for a form. This implements the Get Submissions API

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);
});

formio.loadActions([query], [opts])

Loads the Actions for a given form. This implements the List Actions API

Parameter

Description

query (optional)

opts (optional)

Examples will be very similar to the loadSubmissions API, but will query against the action json objects instead.

formio.availableActions()

Returns a list of available actions that can be added to this form. Implements the Available Actions API.

formio.actionInfo(name)

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.

Submission API Scope

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');

formio.loadSubmission([query], [opts])

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);
});

formio.saveSubmission(submission, [opts])

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);
  });
});

formio.deleteSubmission([opts])

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!');
});

formio.getDownloadUrl([form])

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);
});

formio.uploadFile(storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback)

Uploads a file to the provided storage system. See File Component for specific usage and implementation details.

formio.downloadFile(file, [options])

Downloads a file from the provided storage system. See File Component for specific usage and implementation details.

formio.deleteFile(file, [options])

Deletes a file from the provided storage system. See File Component for specific usage and implementation details

Action API Scope

The following API's are available when the Form.io SDK is instantiated with the action scope like the following illustrates

const formio = new Formio('https://forms.formio.com/myproject/myform/action/234234234234234');

formio.loadAction([query], [opts])

Loads an action for a given form.

Parameter

Description

query (optional)

opts (optional)

Example: Load the action

const formio = new Formio('https://forms.formio.com/myproject/myform/action/234234234234234');
formio.loadAction().then((action) => {
    console.log(action);
});

formio.saveAction(action, [opts])

Creates or Updates an action depending on if an "_id" property is provided within the action json.

Parameter

Description

action

The JSON of the action to save or update. If an "_id" is provided as a property of the action json, then an update operation is performed, otherwise, it will create a new action.

opts (optional)

Example: Create a new action

// Form scope is only required for creating new actions.
const formio = new Formio('https://forms.formio.com/myproject/myform');

formio.saveAction({
	"data": {
		"name": "email",
		"title": "Email",
		"method": ["create"],
		"handler": ["after"],
		"priority": 0,
		"settings": {
			"emails": ["test@example.com"],
			"from": "np-reply@form.io",
			"message": "{{ submission(data, form.components) }}",
			"subject": "New submission for {{ form.title }}.",
			"transport": "default"
		}
	}
}).then((action) => {
  // Prints out the saved action object.
  console.log(action);
});

Example: Update an existing submission

const formio = new Formio('https://forms.formio.com/myproject/myform/action/234234234234234');
formio.loadAction().then((action) => {
  action.title = 'Updated Action Title';
  formio.saveAction(action).then((updated) => {
    console.log(updated);
  });
});

formio.deleteAction([opts])

Deletes an action

Property

Description

opts (optional)

const formio = new Formio('https://forms.formio.com/myproject/myform/action/234234234234234');
formio.deleteAction().then(() => {
    console.log('Action was deleted!');
});

Role API Scope

The following API's are available when the Form.io SDK is instantiated with the role scope like the following illustrates

const formio = new Formio('https://forms.formio.com/myproject/role/234234234234234');

formio.loadRole([opts])

Loads a role json.

Parameter

Description

opts (optional)

Example: Load the role

const formio = new Formio('https://forms.formio.com/myproject/role/234234234234234');
formio.loadRole().then((role) => {
    console.log(role);
});

formio.saveRole(role, [opts])

Creates or Updates a role depending on if an "_id" property is provided within the role json.

Parameter

Description

role

The JSON of the role to save or update. If an "_id" is provided as a property of the role json, then an update operation is performed, otherwise, it will create a new role.

opts (optional)

Example: Create a new role

// Project scope is only required for creating new roles.
const formio = new Formio('https://forms.formio.com/myproject');

formio.saveRole({
	title: 'Employee',
  description: 'A person who belongs to a company.'
}).then((role) => {
  // Prints out the saved role object.
  console.log(role);
});

Example: Update an existing role

const formio = new Formio('https://forms.formio.com/myproject/role/234234234234234');
formio.loadRole().then((role) => {
  role.title = 'Manager';
  formio.saveRole(role).then((updated) => {
    console.log(updated);
  });
});

formio.deleteRole([opts])

Deletes a role

Property

Description

opts (optional)

const formio = new Formio('https://forms.formio.com/myproject/role/234234234234234');
formio.deleteRole().then(() => {
    console.log('Role was deleted!');
});

Utility Methods

formio.isObjectId(id)

Determines if the provided "id" is a valid MongoDB ObjectId

formio.userPermissions([user], [form], [submission])

Fetches an object that describes the users permissions as it pertains to the provided user, form, and submission. If any of these are not provided, then the current object in context is used.

formio.canSubmit()

Returns a promise if the user can submit the form in scope.

const formio = new Formio('https://forms.formio.com/myproject/myform');
formio.canSubmit().then((canSubmit) => {
    if (canSubmit) {
        console.log('The user can submit the form!');
    }
    else {
        console.log('The user cannot submit the form!');
    }
});

Fetch Plugin API

Formio.js can register plugins that can hook into request calls in several ways. Every fetch plugin is defined using the following JSON structure.

const FetchPlugin = {
    /**
     * The priority of the plugin relative to other plugins that determines call 
     * order. Higher numbers have higher priority. If not specified it will 
     * default to a priority of 0.
     */
    priority: 0,
    
    /**
     * An initialization function called when registered with Formio.
     *
     * @param Formio - The static class of the Form.io SDK
     */
    init: (Formio) => {
    
    },
    
    /**
     * A deregistration function called when deregistering with Formio
     *
     * @param Formio - The static class of the Form.io SDK
     */
    deregister: (Formio) => {
    
    }
};

Formio.registerPlugin(FetchPlugin, 'customfetch');

Formio.registerPlugin(plugin, [name])

Registers a fetch plugin with the Form.io SDK.

Parameter

Description

plugin

An instance of the Fetch plugin as described above.

name (optional)

The name of this plugin so that it can be retrieved easily later

Formio.getPlugin(name)

Returns the plugin registered with the given name.

const plugin = Formio.getPlugin('customplugin');

Formio.deregisterPlugin(plugin)

Deregisters a plugin with Form.io SDK. It will call the deregister function on the plugin before deregistering. The plugin argument can be the instance of the plugin or the optional name given when registered. Returns true if the plugin was successfully deregistered, false if the plugin does not exist.

Plugin hooks

Plugins can provide hooks that are invoked at different points in the library. To use a particular hook below, add a function to your plugin with the same name as the hook.

The following are the currently available hooks.

preRequest(requestArgs)

Called before a request. If you return a promise, Formio.js will wait for it to resolve before starting the request.

requestArgs is an object that contains the following properties:

  • formio: The Formio instance calling the request.

  • type: The type of resource being requested (ex: form, forms, submission).

  • url: The url being requested.

  • method: The HTTP request method.

  • data: The HTTP request body, if any.

  • opts: Any opts given to the request

request(requestArgs)

Called before a request, and gives plugins a chance fulfill the request before it is sent. If you return a non-null, non-undefined value (or a promise that resolves to one), that will be used as the results of the request instead of making the default network request.

Only the first highest priority that returns a value will replace the contents. Your plugin's hook will not be called if a higher priority plugin returns a value.

requestArgs is an object that contains the following properties:

  • formio: The Formio instance calling the request.

  • type: The type of resource being requested (ex: form, forms, submission).

  • url: The url being requested.

  • method: The HTTP request method.

  • data: The HTTP request body, if any.

  • opts: Any opts given to the request

wrapRequestPromise(promise, requestArgs)

Called when a request is made and gives plugins access to the promise that is returned when a user makes a request. The promise that is returned from this hook will be returned to the user. You may wrap the original promise or extend the promise chain with this hook. (You must return a promise that uses the original promise, or the promise returned to users will not resolve as expected).

promise is the promise of the request.

requestArgs is an object that contains the following properties:

  • formio: The Formio instance calling the request.

  • type: The type of resource being requested (ex: form, forms, submission).

  • url: The url being requested.

  • method: The HTTP request method.

  • data: The HTTP request body, if any.

  • opts: Any opts given to the request

preStaticRequest(requestArgs)

Same as preRequest hook but used for requests that use the global Formio object instead of a Formio instance. This includes functions like Formio.loadProjects(), Formio.availableActions(), Formio.currentUser().

requestArgs is an object that contains the following properties:

  • url: The url being requested.

  • method: The HTTP request method.

  • data: The HTTP request body, if any.

staticRequest(requestArgs)

Same as request hook but used for requests that use the global Formio object instead of a Formio instance. This includes functions like Formio.loadProjects(), Formio.availableActions(), Formio.currentUser().

requestArgs is an object that contains the following properties:

  • url: The url being requested.

  • method: The HTTP request method.

  • data: The HTTP request body, if any.

wrapStaticRequestPromise(promise, requestArgs)

Same as wrapRequestPromise hook but used for requests that use the global Formio object instead of a Formio instance. This includes functions like Formio.loadProjects(), Formio.availableActions(), Formio.currentUser().

promise is the promise of the request.

requestArgs is an object that contains the following properties:

  • url: The url being requested.

  • method: The HTTP request method.

  • data: The HTTP request body, if any.

Example Plugin

This example plugin will delay all requests by 5 seconds

var DelayPlugin = {
  priority: 0,
  preRequest: function(requestArgs) {
    return new Promise(function(resolve, reject){
      setTimeout(resolve, 5000);
    })
  },
  request: function(args) {
    console.log('Request has been made!', args);
    
    // You can alter the response by changing null to the response you wish to make.
    return Promise.resolve(null);
  }
}

Formio.registerPlugin(DelayPlugin, 'delay');

Query Options (query)

Many of the GET api calls made in this SDK include a variable called query. This is a variable that allows you to pass along query parameters to the URL's that will be used as the API endpoints. The following are properties that can be utilized within the query parameter.

Property

Description

params

An object key-value pair that will be added to the URL as query parameters for the API call.

Example: Load all forms, but filter them by resources and sort them by created descending.

var formio = new Formio('https://form.io/myproject'); formio.loadForms({

params: { type: 'resource', sort: '-created' }

});

The following will produce the following API url.

https://formio.com/myproject/form?type=resource&sort=-created

Fetch Options (opts)

All of the API calls made within this SDK contain a parameter that we will call opts. This is a variable that allows you to pass special options to the fetch methods for the API call being made. The following are properties that can be utilized within the opts parameter.

Property

Description

header

An instance of the Headers class to define the headers of the request

headers

A JavaScript object key-value map of the headers you would like to introduce.

Example:

formio.loadSubmissions({}, {

headers: { 'custom-header': 'Testing' }

});

formio

A custom instance of the Form.io SDK to use for this request.

ignoreCache

Boolean (true) to tell the request to ignore any memory cache of the request. This is useful if you make a request that changes something and then wish to GET additional data without using the cached response.

Example:

formio.loadSubmission({}, {

ignoreCache: true

})

noToken

Boolean (true) to tell the API call to not include the Form.io JWT token along with the request.

namespace

The namespace to use as a prefix of all variables being saved into localStorage for this request. For example, setting this to "test" will save the JWT token into the "testToken" variable instead of the default "formioToken"

Last updated