【问题标题】:Meteor: Custom AutoForm with array of objectsMeteor:带有对象数组的自定义 AutoForm
【发布时间】:2014-11-24 10:21:45
【问题描述】:

我有一个包含对象数组的 SimpleSchema:

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

我正在尝试使用 afEachArrayItem 创建自定义表单,但我不知道如何引用数组中每个对象的属性。

我的模板看起来像这样(去掉了 html):

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

    {{#afEachArrayItem name="fields"}}

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

    {{/afEachArrayItem}}

{{/autoForm}}

在 afFieldInputs 中应该将什么传递给“name”?

【问题讨论】:

    标签: arrays object meteor


    【解决方案1】:

    要访问数组中对象的字段,可以使用:

    this.current
    

    所以要修复上面给出的示例,请使用:

    {{#autoForm collection="things" id="myForm" }}
        {{> afQuickField name='schemaName'}}
    
        {{#afEachArrayItem name="fields"}}
    
            {{> afFieldInput name=this.current.name}}  
            {{> afFieldInput name=this.current.amount}}
    
        {{/afEachArrayItem}}
    
    {{/autoForm}}
    

    我不知道这是否是正确的方法,但它似乎有效。

    【讨论】:

    • 如何添加新行?
    • 否决:此解决方案省略了模板中允许将新元素添加到数组中的部分。
    • @rodamn,您将如何添加允许向数组中添加新元素的模板部分?
    【解决方案2】:

    您可以像这样添加按钮来添加/删除数组项:

    {{#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}}
    

    这将使用 AutoForm 的内置按钮和图标,因此可以根据需要随意修改 HTML。

    【讨论】:

    • 我没有让 autoform-add-item 像你描述的那样工作。还有其他需要设置的参数吗?
    • @LPG 您需要将属性 data-autoform-field="fields" 设置为正确的数组(即更改 fields
    猜你喜欢
    • 2016-05-14
    • 2015-10-25
    • 2015-03-31
    • 1970-01-01
    • 2015-05-19
    • 2015-05-17
    • 2015-01-31
    • 2012-06-20
    • 2015-11-25
    相关资源
    最近更新 更多