BackgroundSync Form
The BackgroundSync Form controller handles form submission with offline support. When the user is online, forms are submitted normally. When offline, form data is queued and automatically retried when the connection is restored.
Installation
Enable the controller in your assets/controllers.json:
{
"controllers": {
"@spomky-labs/pwa-bundle": {
"backgroundsync-form": {
"enabled": true
}
}
}
}Usage
<form {{ stimulus_controller('pwa/backgroundsync-form', {
redirection: path('app_contact_success'),
headers: { 'X-Requested-With': 'XMLHttpRequest' },
}) }}
action="{{ path('app_contact_submit') }}"
method="POST"
{{ stimulus_action('pwa/backgroundsync-form', 'send', 'submit') }}
>
<input type="text" name="name" required>
<input type="email" name="email" required>
<textarea name="message" required></textarea>
<button type="submit">Send</button>
</form>Parameters
params
Object
{ mode: 'cors', cache: 'no-cache', credentials: 'same-origin', redirect: 'follow', referrerPolicy: 'no-referrer' }
Fetch request options.
headers
Object
{}
Custom HTTP headers to include in the request.
redirection
String
null
URL to redirect to after successful form submission.
authenticating
Boolean
false
Whether to sign the request with JWT authentication.
keyIdIndex
String
'default'
The key ID to use for JWT signing (when authenticating is true).
Actions
send
Triggered on form submission. Validates the form, builds the request, and sends it.
Events
invalid-data
-
Form validation failed (HTML5 validation).
unsupported-enctype
-
Form encoding type is not supported.
auth-missing-key
{ keyIdIndex }
JWT authentication enabled but required key is missing.
before:send
{ url, params }
Dispatched before the fetch request is sent.
after:send
{ url, params, response }
Dispatched after the fetch response is received.
error
{ error }
Fetch request failed.
Supported Content Types
The controller supports the following form encoding types:
multipart/form-data- For file uploadsapplication/json- JSON-encoded form dataapplication/x-www-form-urlencoded- Standard URL-encoded form data
How It Works
User submits the form
The controller validates the form using HTML5 validation
Form data is serialized based on the form's
enctypeA
fetchrequest is made with the configured optionsIf the network is available, the request is sent immediately
If the service worker intercepts the request and the user is offline, the request is queued via Background Sync
When the connection is restored, the service worker replays the queued request
On success, the user is optionally redirected to the
redirectionURL
Example: Contact Form with Offline Support
Example: JSON API Form
Related Documentation
Background Sync - Service worker background sync configuration
Sync Broadcast - Monitor sync queue status
Last updated
Was this helpful?