I found this question about how to return a custom validation error on form submit. This works for individual field errors, but how do I return a generic form error not pertaining to a particular field? I want to return a custom form submission error that appears above the submit button. The error I want to return doesn't have anything to do with a specific field, so I want to send back a generic error message that just shows at the bottom of the form.
There's no documentation on this that I can find.
First set your custom error to $form_data['errors'] in your submit hook.
$form_data['errors'] = ["My Custom Error Message"];
Now you need to display this error using front-end code.
Hook into "submit:response"
on the front-end.
var mySubmitController = Marionette.Object.extend({
initialize: function () {
this.listenTo(
Backbone.Radio.channel("forms"),
"submit:response",
this.actionSubmit
);
},
actionSubmit: function (response) {
const errorNotice = document.querySelector(".nf-before-form nf-section");
errorNotice.innerHTML = "";
if (!response.errors || !response.errors.length) {
return;
}
const errors = response.errors;
errorNotice.insertAdjacentHTML(
"afterbegin",
"<strong>Your form submission encountered the following errors:</strong>"
);
errorNotice.insertAdjacentHTML("beforeend", "<ul>");
errors.forEach((error) => {
errorNotice.insertAdjacentHTML("beforeend", `<li>${error}</li>`);
});
errorNotice.insertAdjacentHTML("beforeend", "</ul>");
errorNotice.scrollIntoView({
behavior: "smooth"
});
}
});
jQuery(document).ready(function ($) {
new mySubmitController();
});