initial
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* RsvAdminForm — shared submit handler for wp-admin forms.
|
||||
*
|
||||
* Serializes a <form> to JSON (via RsvFormEncoder), sends it to the form's
|
||||
* `action` using the HTTP verb in `data-method`, always attaches the REST
|
||||
* nonce, and reports the outcome through show_notice(). The only part that
|
||||
* legitimately differs between forms — shaping the request body — is handled
|
||||
* by the optional `transform(body, form)` hook.
|
||||
*
|
||||
* Usage:
|
||||
* RsvAdminForm.bind(my_form, {
|
||||
* transform: (body, form) => ({ ...body, block_size: parseInt(body.block_size) }),
|
||||
* refresh: () => my_datagrid.refresh(),
|
||||
* });
|
||||
*/
|
||||
const RsvAdminForm = {
|
||||
// Attach a submit listener that sends the form as JSON.
|
||||
bind(form, options = {}) {
|
||||
if (!form) return;
|
||||
form.addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
RsvAdminForm.submit(form, options);
|
||||
});
|
||||
},
|
||||
|
||||
// Send the form now. Returns the fetch promise.
|
||||
submit(form, { transform, refresh, onSuccess } = {}) {
|
||||
let body = RsvFormEncoder.encode_form(form);
|
||||
if (transform) body = transform(body, form);
|
||||
|
||||
// `form.method` always returns a string (default 'get'), so default to POST
|
||||
// explicitly unless the view opted into a verb via data-method.
|
||||
const method = (form.dataset.method || 'POST').toUpperCase();
|
||||
|
||||
return fetch(form.action, {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'X-WP-Nonce': ReservairServiceAPI.nonce,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
.then(async (response) => {
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(data?.error || data?.message || 'Request failed');
|
||||
return data;
|
||||
})
|
||||
.then((data) => {
|
||||
show_notice(form, 'success', form.dataset.successMsg ?? 'Saved.');
|
||||
if (refresh) refresh();
|
||||
if (onSuccess) onSuccess(data);
|
||||
})
|
||||
.catch((error) => show_notice(form, 'error', error.message));
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user