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

How to create a form with an array of inputs #198

Open
bytesoverflow opened this issue Jan 9, 2017 · 4 comments
Open

How to create a form with an array of inputs #198

bytesoverflow opened this issue Jan 9, 2017 · 4 comments

Comments

@bytesoverflow
Copy link

bytesoverflow commented Jan 9, 2017

How would i go about creating a form that outputs:

<input name="name" type="text">
<input name="properties[0][var1]" type="text">
<input name="properties[0][var2]" type="checkbox">
<input name="properties[1][var1]" type="text">
<input name="properties[1][var2]" type="checkbox">

or alternatively if thats not possible:

<input name="name" type="text">
<input name="properties[var1]" type="text">
<input name="properties[var2]" type="checkbox">
<input name="properties[var1]" type="text">
<input name="properties[var2]" type="checkbox">

I need to add the array fields to the form dynamically based on the number of fields in the document i retrieve from mongo.

The data i need to bind to the form is in the following format:

{
name: 'xxxxx'
properties: [
    {var1: 'yyy', var2: true },
    {var1: 'zzz', var2: false}
 ]
}

I thought about creating a form using fields.array() for the properties attribute and using a custom widget that renders fields.object instead of fields.string but cant seem to get it working.

Is there a simple solution?

@ljharb
Copy link
Collaborator

ljharb commented Jan 10, 2017

The former would be the only way to do it; in the latter case, the second pair would overwrite the first because they have the same name.

The following should work, but doesn't:

var f = forms.create({
  someName: fields.string(),
  someOtherName: [{
    var1: fields.string(),
    var2: fields.boolean()
  }, {
    var1: fields.string(),
    var2: fields.boolean()
  }, {
    var1: fields.string(),
    var2: fields.boolean()
  }, {
    var1: fields.string(),
    var2: fields.boolean()
  }]
});
f.toHTML()

thus instead of hardcoding it, you'd build up that someOtherName array dynamically.

@bytesoverflow
Copy link
Author

When I run that example I get the following error:

TypeError: f.fields[k].bind is not a function
at /Users/Toby/Development/Repos/mpg/node_modules/forms/lib/forms.js:40:47

@ljharb
Copy link
Collaborator

ljharb commented Jan 11, 2017

The following should work, but doesn't:

@reneweteling
Copy link

Yep, same here

form.fields[k].toHTML is not a function
TypeError: form.fields[k].toHTML is not a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants