-
-
Notifications
You must be signed in to change notification settings - Fork 73
Multiple forms are possible by setting options.applyAction = false
to all but one, and the forms won't interfere with each other, which can happen as they both both update $page.status
and $page.form
.
When applyAction is false, you need to handle page updates yourself for that form (invalidateAll, applyAction, etc), as described in SvelteKit's use:enhance docs.
You can of course set applyAction = false
on all forms, but usually there is a "main" form on the page, which should update $page
. But if you have several equally important forms on the page, you may instead use the onResult
event to set page status in combination with applyAction, as described in the SvelteKit docs. But beware about error page rendering then. An error
result will render the nearest +error
boundary, clearing out the page and form data.
Note that options.invalidateAll
is true
as default, so if you want to make a form completely self-contained, neither touching $page
nor running any load
functions on success
set it to false
as well.
See this wiki entry for a list of default values, used when data for a schema field is missing.
Yes, you can set a default
schema value to anything you'd like it to be. For example with the classic "agree to terms" checkbox:
const schema = z.object({
age: z.number().positive().default(NaN),
agree: z.literal(true).default(false as true)
})
This looks strange, but will ensure that an age must be selected and the agree checkbox is unchecked as default, and will only accept true as a value. Just note that you will bypass the type system with this, so the default value will not correspond to the data type, but this will usually not be a problem since form.valid
will be false
if the default values are posted as-is, and that should be the main determinant whether the data is trustworthy.
When you start to configure the library to suit your stack, it's recommended to create an object with default options that you will refer to instead:
import { superForm } from 'sveltekit-superforms/client';
import type { AnyZodObject } from 'zod';
export function yourSuperForm<T extends AnyZodObject>(
...params: Parameters<typeof superForm<T>>
) {
return superForm(params[0], {
// Your defaults here
errorSelector: '.has-error',
delayMs: 300,
...params[1]
});
}
Currently, file uploads are not handled with sveltekit-superforms
. The recommended way to do it is to grab the FormData
and extract the files from there, after validation:
export const actions = {
default: async ({ request }) => {
const formData = await request.formData();
const form = await superValidate(formData, schema);
if (!form.valid) return fail(400, { form });
const file = formData.get('file');
if (file instanceof File) {
// Do something with the file.
}
return { form };
}
} satisfies Actions;