Skip to content

feat: allow setting dynamic values in remote forms #16160

Description

@jdgamble555

Describe the problem

Currently, there is no built-in way to set the initial data for a remote form if the data is dynamic.

Image

If we set the data, it does NOT get updated automatically when the the runes get updated, since setting the initial values themselves are not dynamic.

Note: That matters because .as(type, value) sets the input value, but it does not fully initialize the form field state in the same way as fields.set(...).

This becomes awkward for edit forms, generated forms, shared form components, or any case where the values come from a record rather than being passed field-by-field.

Describe the proposed solution

updateChapterForm.fields.default(() => ({
  courseId: initialData.course_id,
  chapterId: initialData.id,
  title: initialData.title,
}));

or

<form
  {...updateChapterForm}
  values={() => ({
    courseId: initialData.course_id,
    chapterId: initialData.id,
    title: initialData.title,
  })}
>

Alternatives considered

Currently, I have created a workaround like this:

import type { RemoteForm, RemoteFormInput } from '@sveltejs/kit';

type RemoteFormFields<T extends RemoteFormInput, R = unknown> = Parameters<
    RemoteForm<T, R>['fields']['set']
>[0];

export function initForm<T extends RemoteFormInput, R = unknown>(
    form: RemoteForm<T, R>,
    getter: () => RemoteFormFields<T, R>
) {
    let hydrated = false;

    const new_value = getter();

    form.fields.set(new_value);

    $effect(() => {
        const values = getter();

        if (!hydrated) {
            hydrated = true;
            return;
        }

        form.fields.set(values);
    });
}

and use it like so:

initForm(updateChapterForm, () => ({
    courseId: initialData.course_id,
    chapterId: initialData.id,
    title: initialData.title
}));

Obviously, this is not clean and requires boilerplate to work.

Importance

would make my life easier

Additional Information

The important behavior would be:

  1. Initialize the remote form field state from an object.
  2. Work with dynamic values from loaded data.
  3. Avoid requiring every field to pass its value manually through .as(type, value).
  4. Avoid clobbering user input during hydration.
  5. Optionally allow reinitialization when a key changes, such as when editing a different record.

Related:

I am open to any solution that avoids the biolerplate.

J

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions