Using remote forms + enhance is it possible to modify a form value before its sent to the server? #15760
I have a very basic form where I basically just ask the user to enter a title. This would then trigger a snapshot save of a fabric js canvas which i then want to submit to my server to save. I can do this very easily with a command. But I am wondering before I abandon forms is it possible to achieve this using them. e.g via command I can do: |
Replies: 2 comments 1 reply
|
Yes — this is a good use case for With the plain SvelteKit API it looks like this: <form
use:enhance(({ formData, submit }) => {
formData.set('title', title);
formData.set('canvasJSON', JSON.stringify(canvasRegistry.get().map((c) => c.toJSON())));
formData.set('entitiesJSON', JSON.stringify([...entities.entries()]));
return submit({ formData });
})
>If your helper exposes data.set('canvasJSON', serialised)
data.set('entitiesJSON', entitiesJSON)
await submit()I’d usually pair this with hidden fields as a fallback, so the server action still has a predictable schema: <input type="hidden" name="canvasJSON" />
<input type="hidden" name="entitiesJSON" />So no, you don’t need to abandon forms here. Forms + |
|
Yeah, you can do this with SvelteKit's <form
method="POST"
action="?/save"
use:enhance={({ formData, cancel }) => {
const serialised = designEngine.seraliseCanvas();
formData.set('canvasJSON', JSON.stringify(
canvasRegistry.get().map(c => c.toJSON())
));
formData.set('entitiesJSON', JSON.stringify(
Array.from(entities.entries())
));
// don't cancel — let the form submit with the modified data
return async ({ result }) => {
// handle result
};
}}
>
<input type="text" name="title" />
<button type="submit">Save</button>
</form>The You don't need hidden inputs for // +page.server.ts
export const actions = {
save: async ({ request }) => {
const data = await request.formData();
const title = data.get('title');
const canvasJSON = data.get('canvasJSON');
const entitiesJSON = data.get('entitiesJSON');
// save to DB
}
};One thing to watch: if your canvas data is large (multiple MB), form submissions might be slow. In that case the command pattern you already have is probably better since you can add progress indicators, streaming, etc. But for normal-sized payloads, this works fine. |
See #14477 (comment)