Skip to content

JavaScript API

Travis Tidwell edited this page Aug 17, 2017 · 34 revisions

The JavaScript API is a minimalistic API library that allows you to work with the Form.io API's within JavaScript.

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.

var formio = new Formio(<endpoint>);

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.

Project Context

The project context is the top-most level of the Form.io API's. This context provides project level information for anything within your project. To declare the Formio object at this context, you simply need to provide the URL for your project like so.

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

Project APIs

formio.loadProject()

This will load the current project in context

Example

var formio = new Formio('https://myproject.form.io');
formio.loadProject().then(function(project) {
  console.log(project);
});

formio.saveProject(<project>)

Saves the parent Project, using the given payload.

Example

var formio = new Formio('https://myproject.form.io');
formio.loadProject().then(function(project) {
  project.title = 'Changed title';
  formio.saveProject(project).then(function(saved) {
    console.log(saved);
  });
});

formio.deleteProject()

Deletes the parent Project.

Example

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

formio.loadForms(<query>)

Loads all of the Forms within a project.

Example

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

// Load all forms within a project
formio.loadForms({params: {type: 'form'}}).then(function(forms) {
  console.log(forms);
});

// Load all resources within a project
formio.loadForms({params: {type: 'resource'}}).then(function(resources) {
  console.log(resources);
});

Form Context

Form context is provided to the Formio class by passing along the URL of the form you wish to load.

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

The following API methods are available for this context.

All Project Context API's

formio.loadForm()

Loads the given Form.

var formio = new Formio('https://myproject.form.io/myform');
formio.loadForm().then(function(form) {
  console.log(form);
});

formio.saveForm()

Saves the given Form, using the given payload.

var formio = new Formio('https://myproject.form.io/myform');
formio.loadForm().then(function(form) {
  form.title = 'Changed title';
  formio.saveForm(form).then(function(changed) {
    console.log(changed);
  });
});

formio.deleteForm()

Deletes the given Form.

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

formio.loadSubmissions(<query>)

Loads all the submissions for this specific form.

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

// Load all submissions whose first name is "Travis"
formio.loadSubmissions({params:{'data.firstName':'Travis'}}).then(function(submissions) {
  console.log(submissions);
});

formio.loadActions(<query>)

Loads all actions available to this form.

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

// Give me all email actions attached to this form.
formio.loadActions({params:{type: 'email}}).then(function(emailActions) {
  console.log(emailActions);
});

formio.canSubmit()

Determines if the currently logged in user can submit this form.

var formio = new Formio('https://myproject.form.io/myform');
formio.canSubmit().then(function(canSubmit) {
  if (canSubmit) {
    console.log('This user can submit this form!');
  }
});

formio.loadAction() - Loads the given Action.

  • Requires the initial path to be a specific Action URL.

formio.saveAction() - Saves the given Action.

  • Requires the initial path to be a specific Action URL.

formio.deleteAction() - Deletes the given Action.

  • Requires the initial path to be a specific Action URL.

formio.loadActions() - Loads all of the Actions for a given Form.

  • Requires the initial path to be a specific Form URL.

formio.availableActions() - Loads all the Actions available for a given Form.

  • Requires the initial path to be a specific Form URL.

formio.availableInfo() - Loads all the settings available for a given Action.

  • Requires the initial path to be a specific Form URL.

formio.loadSubmissions() - Loads all of the Submissions for a given Form.

  • Requires the initial path to be a specific Form URL.

formio.loadSubmission() - Loads the given Submission.

  • Requires the initial path to be a specific Submission URL.

formio.saveSubmission() - Saves the given Submission, using the given payload.

  • Requires the initial path to be a specific Submission URL.

formio.deleteSubmission() - Deletes the given Submission.

  • Requires the initial path to be a specific Submission URL.

Examples

Loading a Project

var formio = new Formio('https://myproject.form.io');
formio.loadProject().then(function(project) {
  console.log(project);

  // Load all the forms.
  formio.loadForms().then(function(forms) {
    console.log(forms);
  });
});

Loading a Form

var formio = new Formio('https://myproject.form.io/myform');
formio.loadForm().then(function(form) {
  console.log(form);
});

Loading a Submission

var formio = new Formio('https://myproject.form.io/myform/submission/5736076036db24c3c679e778');
formio.loadSubmission().then(function(submission) {
  console.log(submission);
});

In addition, this library also provides plugin support to the submissions being made so that libraries like our Offline Mode can be utilized.

Static Methods

Formio.setBaseUrl(<url>)

Sets the base URL to tell this library which root API you are talking with.

Formio.setBaseUrl('https://forms.myserver.com');

Formio.getBaseUrl()

Gets the base url configuration.

Formio.setProjectUrl(<url>)

Sets the project endpoint url.

Formio.setProjectUrl('https://myproject.form.io');

Formio.setToken(<token>)

Sets the JWT Auth token for this library.

Formio.getToken()

Gets the current users JWT token.

Formio.currentUser()

Retrieves the current user from the Project api.

Formio.currentUser().then(function(user) {
  console.log(user);
});

Formio.accessInfo()

Fetches the accessInfo from the current baseURL project.

Formio.accessInfo().then(function(access) {
  console.log(access);
});

Formio.setUser(<user>)

Sets the current user object within localStorage.

Formio.getUser()

Gets the current logged in user object out of localStorage.

Formio.loadProjects(<query>)

Loads all of the projects that your account has access to.

Formio.loadProjects().then(function(projects) {
  console.log(projects);
});

Formio.clearCache()

Clears out the static http request cache. This will ensure that the next API request actually hits the network and gets new data.

Formio.clearCache();
Formio.loadProjects().then(function(projects) {
  console.log(projects);
});

Formio.logout()

Logs out of the current API and removes the stored JWT token.

Plugin API

Formio.js can register plugins that can hook into request calls in several ways.

Plugin methods

Formio.registerPlugin(plugin, [name])

Registers a plugin with Formio.js. An optional name parameter can be provided to be used with Formio.getPlugin().

A plugin must be an object, and can have any of the following optional properties:

  • priority: 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.
  • init: An initialization function called when registered with Formio. It will receive the global Formio object as its first parameter.
  • deregister: A deregistration function called when deregistering with Formio. It will receive the global Formio object as its first parameter.

See below on using hooks in your plugin.

Formio.getPlugin(name)

Returns the plugin registered with the given name.

Formio.deregisterPlugin(plugin)

Deregisters a plugin with Formio.js. 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.

Formio.events

This is an EventEmitter that you may use as an event publish/subscribe system in your plugins.

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

Formio.registerPlugin(DelayPlugin, 'delay');
// Can later access with
// Formio.getPlugin('delay')
Clone this wiki locally