Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: Custom AutoForm with array of objects

I have a SimpleSchema which includes an array of objects:

Things.attachSchema( new SimpleSchema({
    name: {
        type: String,
        label: "Name",
        max: 50
    },
    fields: { 
        type: [Object],
    },
    fields.$.name: {
        type: String
    },
    fields.$.amount: {
        type: Number
    }
}) )

I'm trying to create custom form making use of afEachArrayItem, but I can't work out how to refer to the attributes of each object within the array.

My template looks like this (with html stripped out):

{{#autoForm collection="things" id="myForm" }}
    {{> afQuickField name='schemaName'}}

    {{#afEachArrayItem name="fields"}}

        {{> afFieldInput name="name"}  
        {{> afFieldInput name="amount"}

    {{/afEachArrayItem}}

{{/autoForm}}

What should be passed to "name" in the afFieldInputs?

like image 354
Paul Ellery Avatar asked Sep 29 '14 22:09

Paul Ellery


2 Answers

To access the fields of the objects within the array, you can use:

this.current

So to fix the example given above, use:

{{#autoForm collection="things" id="myForm" }}
    {{> afQuickField name='schemaName'}}

    {{#afEachArrayItem name="fields"}}

        {{> afFieldInput name=this.current.name}}  
        {{> afFieldInput name=this.current.amount}}

    {{/afEachArrayItem}}

{{/autoForm}}

I don't know if this is the correct way to do this, but it seems to work.

like image 114
Paul Ellery Avatar answered Nov 12 '22 07:11

Paul Ellery


You can add buttons to add/remove the array items as so:

{{#autoForm collection="things" id="myForm" }}
    {{> afQuickField name='schemaName'}}

    {{#afEachArrayItem name="fields"}}

        <button type="button" class="btn btn-primary autoform-remove-item"><span class="glyphicon glyphicon-minus"></span></button>
        {{> afFieldInput name=this.current.name}}  
        {{> afFieldInput name=this.current.amount}}

    {{/afEachArrayItem}}
    <button type="button" class="btn btn-primary autoform-add-item" data-autoform-field="fields"><span class="glyphicon glyphicon-plus"></span></button>

{{/autoForm}}

This will use the built-in buttons and icons for AutoForm, so feel free to modify the HTML as necessary.

like image 36
rhlsthrm Avatar answered Nov 12 '22 06:11

rhlsthrm