Forms Helpers Widget¶
Summary¶
Small helpers for posting forms with the Cosmos antiforgery token and basic element checks.
- Location (source):
Editor/wwwroot/lib/cosmos/forms.js - Exposed functions:
ccms___ElementExists(element: any): booleanccms___GetXsrfToken(): Promise<string>— fetches an antiforgery token from/ccms__antiforgery/tokenresponse headerXSRF-TOKENccms___PostForm(endpoint: string, formName: string): Promise<Response>— posts the named form with headerRequestVerificationToken
Outcome¶
After completing this guide, you should be able to submit forms through SkyCMS with a valid antiforgery token and clear error handling.
Steps¶
- Add a
<form>element with anameattribute to your page. - Include
forms.jsin your layout or page template:<script src="/lib/cosmos/forms.js"></script>. - Attach a
submitevent listener that callsevent.preventDefault(). - Inside the handler, call
await ccms___PostForm(endpoint, formName)with your API endpoint and form name. - Check
response.okand surface errors to the user as needed. - Verify that a valid submission reaches the endpoint and passes antiforgery validation.
Requirements¶
- Server endpoint
/ccms__antiforgery/tokenmust return a response with anXSRF-TOKENheader. - Target form must be accessible via
document.forms[formName].
Simple usage¶
<form name="contactForm" id="contactForm">
<input name="email" type="email" required />
<textarea name="message" required></textarea>
<button id="btnSubmit" type="submit">Send</button>
</form>
<script src="/lib/cosmos/forms.js"></script>
<script>
document.getElementById('contactForm').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const resp = await ccms___PostForm('/Contact/Send', 'contactForm');
if (!resp.ok) throw new Error('Request failed: ' + resp.status);
alert('Thank you!');
} catch (err) {
console.error(err);
alert('Sorry, please try again.');
}
});
</script>
Notes¶
ccms___PostFormbuilds aFormData(form)and sends it with headerRequestVerificationTokenusing the value retrieved fromccms___GetXsrfToken().- Handle errors by checking
response.okand reading body as needed.
Verification¶
This integration is complete when form submission succeeds for valid input, antiforgery validation passes, and failed requests surface actionable errors to users.