In this article you will learn what the SiteManager form events are. We will also show an example on how to cancel a certain action.
With events, it is possible to insert certain actions when form events are happening. For example, you could add your own custom validation with the validate event, so you will know for sure that the data you gather is valid.
There are 4 events that can be used. These events are listed below:
- mount: Event that will fire when the form has been mounted.
- validate: Event that will fire when the form validates.
- submit.before: Event that will fire after the form has validated, but before the data is being submitted.
- submit.after: Event that will fire after the form has been submitted.
Starting out
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();
}
});
});
You can use the smForm variable to activate your events.
Examples
In the following examples, we will demonstrate how you can use these events.
You can use a return false statement to cancel the continuation of the form. For example, if your custom validation fails, you probably don't want the form to submit.
Add custom validation
smForm.on('validate', function() {
const phoneField = this.form.querySelector('[data-phone]');
if (!phoneField.value.startsWith('+32') {
return false;
}
});
Cancel a form action
Sometimes it could be necessary to execute form actions dynamically. For example, you might want to only send the data to Google Sheets, when an opt-in has been selected. This is possible by combining the submit.before event with the removeAction function.
smForm.on('submit.before', function() {
const optIn = this.form.querySelector('[data-optin]');
if (!optIn.checked) {
this.removeAction('sheets');
}
});