【问题标题】:How to add a relationship or reference with AutoForm in Meteor?如何在 Meteor 中使用 AutoForm 添加关系或引用?
【发布时间】:2015-10-09 00:51:19
【问题描述】:

我使用meteor-autoform 在集合中插入文档。我的Items 有一个字段groupId。我如何在提交商品表单时插入此组 ID。

<template name="itemForm">
  {{#autoForm type="insert" collection=Collections.Items}}
    {{> afQuickField name="name"}}
    <div class="form-group">
      <button type="submit" class="btn btn-primary">Add item</button>
      <button type="reset" class="btn btn-default">Reset Form</button>
    </div>
  {{/autoForm}}
</template>

我可以创建另一个包含我的组 ID 的字段,但我不希望用户看到这个字段。

如何设置groupId“幕后”?

【问题讨论】:

  • 在您的字段中,您可以添加autoform: {omit: true} 以隐藏表单中的字段

标签: javascript meteor meteor-autoform simple-schema


【解决方案1】:

为此,您需要a hook。您还需要为表单设置一个 ID,比如addItemForm

//Anywhere in your client code
Autoform.hooks({
  addItemForm : {
    onSubmit : function(doc) {
      doc.groupId = /*Get the group id*/;
      this.done(); //We've finished
      return true; //Let autoForm do his default job now
    }
  }
});

【讨论】:

  • 酷。我如何获得组ID?现在,我在 Router.route('/group/:_id', {}); 内获取带有 this.params._id 的 ID
  • 如果您的 groupId 是唯一的,您可以将其传递给全局变量。另一种选择是在服务器上设置它......或者,为了提供更好的控制,您可以在表单中使用一种方法。 See the type here.
【解决方案2】:

我认为一种解决方案不是向用户显示此选项。您还需要在该字段中添加optional:true,这样在您提交表单时它仍然有效。

然后使用钩子,你应该能够添加任何你想要的其他数据

文档可用hooks on autoform

我通常修改before insert上的文档

AutoForm.hooks({
  myFormId: {
    before: {
      insert: function(doc, template) {
        //modify the document here
      }
    }
})

【讨论】:

    【解决方案3】:

    如果模板的数据上下文可用,您可以使用doc=this

    例如:

    <template name="itemForm">
      {{#autoForm id="insert-item-form" type="insert" collection=Collections.Items doc=this}}
        {{> afQuickField name="name"}}
        <div class="form-group">
          <button type="submit" class="btn btn-primary">Add item</button>
          <button type="reset" class="btn btn-default">Reset Form</button>
        </div>
      {{/autoForm}}
    </template>
    

    进一步的结果,你可以设置一个钩子,它会在插入操作之前被触发:

    var itemsHooks = {
        before: {
            insert: function (doc) {
                doc.groupId = this.currentDoc._id;
                return doc;
            }
        }
    };
    
    AutoForm.addHooks('insert-item-form', itemsHooks);
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 2015-09-22
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2016-02-08
      • 2020-09-26
      • 2015-09-20
      • 2015-05-08
      相关资源
      最近更新 更多