ciscoheat / sveltekit-superforms

Making SvelteKit forms a pleasure to use!
https://superforms.rocks
MIT License
2.26k stars 65 forks source link

Form Fields Not Recognized in sveltekit-superforms Despite Correct Schema and Setup #513

Open ethanfox opened 4 days ago

ethanfox commented 4 days ago

Description I'm encountering a critical issue with sveltekit-superforms where none of the form fields are being recognized. Despite following the documentation and ensuring that dataType: 'json' is set and use:enhance is applied, the form initialization fails, and I receive errors indicating that all fields are missing from the form object. This issue affects all fields defined in the schema.

Schema

import { z } from 'zod';

export const createUserSchema = z.object({
    userName: z.string().min(1, 'Username is required'),
    firstName: z.string().min(1, 'First name is required'),
    lastName: z.string().min(1, 'Last name is required'),
    password: z.string().min(6, 'Password must be at least 6 characters'),
    confirmPassword: z.string().min(6, 'Confirm password must be at least 6 characters'),
    isSystemAdmin: z.boolean(),
    isEnabled: z.boolean(),
    tags: z.array(z.string()),
    roles: z.array(z.string()),
    permissions: z.string(),
    description: z.string().optional()
}).refine(data => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ['confirmPassword']
});

Form Initialization

const { form, errors, enhance } = superForm({
        dataType: 'json',
        validators: zodClient(createUserSchema),
        initialValues: {
            userName: '',
            firstName: '',
            lastName: '',
            password: '',
            confirmPassword: '',
            isSystemAdmin: false,
            isEnabled: true,
            tags: [],
            roles: [],
            permissions: '',
            description: ''
        },

        onSubmit: async ({ cancel }) => {
            if (form.password !== form.confirmPassword) {
                toastError('Passwords do not match');
                return;
            }
            cancel();

            try {
                const userRequest = {
                    userName: form.userName,
                    firstName: form.firstName,
                    lastName: form.lastName,
                    description: form.description || '',
                    password: form.password
                };

                const newUser = await createUser(userRequest);
                toastSuccess('User created successfully');
                goto(`/detail?id=${newUser.id}&type=user`);
            } catch (error) {
                toastError(error.toString() || 'Failed to create user');
            }
        }
    });

Steps to Reproduce

  1. Initialize a form using superForm with the above schema.
  2. Set dataType: 'json' and apply use:enhance to the form element.
  3. Bind form fields and attempt to handle form submission.
  4. Observe errors indicating that none of the fields exist in the form object.

Expected Behavior The form should initialize correctly with the provided schema and initial values, allowing for client-side validation and submission handling without errors.

Actual Behavior Page doesnt load. Console log message:

Unhandled Promise Rejection: Error: Object found in form field "validators". Set the dataType option to "json" and add use:enhance to use nested data structures. More information: https://superforms.rocks/concepts/nested-data

Issues with handling nested data structures despite setting dataType: 'json'.

Additional Context SvelteKit version: 2.8.1 sveltekit-superforms version: 2.20.1 Browser: Chrome Operating System: MacOS 15.1

ciscoheat commented 3 days ago

What is initialValues? They are not used in superForm, and that's not needed either as the Zod adapter handles default values.

The check for objects is only made when dataType is set to 'json', and as the "validators" field isn't part of your schema, I suspect you are passing the wrong object somewhere. If you try to make a MRE with the following link, I'm sure you'll find the problem somewhere. Otherwise, I'll take a closer look.

https://sveltelab.dev/github.com/ciscoheat/superforms-examples/tree/zod