chainlist / svelte-forms

Svelte forms validation made easy
MIT License
401 stars 36 forks source link

[REQUEST] addField() method #101

Open rogrdat opened 1 year ago

rogrdat commented 1 year ago

In forms fields can be added dynamically. Currently a form instance can be set only at initialization. Need this feature to handle dynamic scenarios

Ideally an "addField" or similar method to dynamically add 1 or more fields to a form instance.

BrianIto commented 1 year ago

In @angular/forms they covered that case gracefully. They use something called form.array, and you can push new controls (they are the same idea as fields here) to work with auto generated inputs (a common case is adding something to a list and this list have custom inputs to change an specific parameter).

Could we use something like it?

pboguslawski commented 6 months ago

Workaround that works for us:

(1) patch svelte-forms (i.e using patch-package) for access to Field type (please consider fixing it in this repository):

diff --git a/node_modules/svelte-forms/index.d.ts b/node_modules/svelte-forms/index.d.ts
index 4393bab..e1c459e 100644
--- a/node_modules/svelte-forms/index.d.ts
+++ b/node_modules/svelte-forms/index.d.ts
@@ -3,4 +3,4 @@ export { form } from './form.js';
 export { field } from './field.js';
 export { style } from './use.style.js';
 export { combined } from './combined.js';
-export { defaultFieldOptions as defaultFieldOptions } from './types.js';
+export { defaultFieldOptions as defaultFieldOptions, Field } from './types.js';

(2) use

import type { Field } from 'svelte-forms';

[...]

// Prepare form field list dynamically.
var formFields: (Writable<Field<unknown>> | Readable<Field<unknown>>)[];
$: {
    formFields = [
        givenNameField,
        surnameField,
    ];
    if (createMode) {
        // Email field is present in the form in create mode only.
        formFields.push(emailField);
    }
}
$: userForm = form(...formFields);