How to connect custom services to a form.

In this article you will learn how to add your own custom actions to your SiteManager form. Connect external services and collect the data from the end user.

Out of the box, SiteManager provides a few services (actions) that you can connect to. With our developer tools, it is possible to connect a limitless amount of services to your form. You can do this by pushing a new action to the forms postAction function.

Inside the JavaScript of the form component, you will find the following code.

document.addEventListener('DOMContentLoaded', e => {

const formNodes = Array.prototype.slice.call(document.querySelectorAll('[data-form]'));

formNodes.forEach(formNode => {
if (formNode.dataset.form === 'sm-unique-style') {
const smForm = new SM_Form(formNode, {
[:cssdata:]
});

smForm.mount();
}
});

});

This code initializes the form builder with all configured functionalities. As stated above, you can use the function postAction to push your own actions to the form.

smForm.postAction(function(resolve, reject) {
const form = this.form;
const data = new FormData(this.form);

/* Write some magic to parse and send the data to your service */

switch (result.status) {
case 201:
resolve(result.data); /* Success! */
break;
case 400:
reject(result.data); /* Error! */
break;
}
});

Your action will be executed when the user submits the form and when the form has been validated. You can access the form and its data here, to send the data to the service you are connecting to.

Be sure to resolve or reject the action. Without it, the submit event will never finish and the user won't have an indication that the form has been sent.

Displaying errors

It is also possible to show a custom error with your new action. The error will be added to the list of errors and will look native to the form component.

To display a custom error, you need to call the setError method and pass an object with your action name and the error message. The action name will be shown, so the user knows which action is showing which error.

smForm.postAction.setError({
action: 'New Action',
message: 'Custom error message from your action'
});