/**
* Import components/ContactForm7.js to any page contains contact-form-7 to
* normalize form error handling and events
* @module ContactForm7
*/
import $ from "jquery";
const showAlert = (form, message, type) => {
const html = `
<div class="alert alert-${type} alert-dismissible fade show" role="alert">
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>`;
$(form).prepend($(html));
};
const clearFormValidation = (form) => {
const $form = $(form);
$form.removeClass("was-validated");
$form.find(".valid-feedback, .invalid-feedback").remove();
$form.find(".form-control").removeClass("is-valid").removeClass("is-invalid");
$form.find(".alert").remove();
};
document.addEventListener(
"wpcf7submit",
function (event) {
clearFormValidation(event.target);
const {
detail: { apiResponse },
} = event;
const { status, invalid_fields, message } = apiResponse;
switch (status) {
case "mail_sent":
showAlert(event.target, message, "success");
break;
default:
showAlert(event.target, message, "danger");
invalid_fields.map((field) => {
const $field = $(`#${field.idref}`);
const $wrapper = $field.parent();
$field.addClass("is-invalid");
$wrapper.append(
`<div class="invalid-feedback">${field.message}</div>`,
);
});
break;
}
},
false,
);
Source