svelte-forms icon indicating copy to clipboard operation
svelte-forms copied to clipboard

[REQUEST] addField() method

Open rogrdat opened this issue 3 years ago • 2 comments

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.

rogrdat avatar Jan 04 '23 15:01 rogrdat

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?

BrianIto avatar Jan 08 '23 00:01 BrianIto

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);

pboguslawski avatar Feb 21 '24 17:02 pboguslawski