Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REQUEST] addField() method #101

Open
rogrdat opened this issue Jan 4, 2023 · 2 comments
Open

[REQUEST] addField() method #101

rogrdat opened this issue Jan 4, 2023 · 2 comments
Assignees
Labels
enhancement New feature or request

Comments

@rogrdat
Copy link

rogrdat commented Jan 4, 2023

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 rogrdat added the enhancement New feature or request label Jan 4, 2023
@BrianIto
Copy link

BrianIto commented Jan 8, 2023

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants