forms icon indicating copy to clipboard operation
forms copied to clipboard

How to create a form with an array of inputs

Open tobydeh opened this issue 8 years ago • 4 comments

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?

tobydeh avatar Jan 09 '17 16:01 tobydeh

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.

ljharb avatar Jan 10 '17 21:01 ljharb

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

tobydeh avatar Jan 11 '17 19:01 tobydeh

The following should work, but doesn't:

ljharb avatar Jan 11 '17 22:01 ljharb

Yep, same here

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

reneweteling avatar Dec 07 '17 15:12 reneweteling