如何在 Meteor 中添加与自动表单的关系或引用

How to add a relationship or reference with AutoForm in Meteor?

本文关键字:表单 关系 引用 Meteor 添加      更新时间:2023-09-26

我使用 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

为此,您需要一个钩子。您还需要为表单设置一个 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
    }
  }
});

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

然后使用钩子,您应该能够添加所需的任何其他数据

文档在自动表单上可用钩子

我通常会修改before insert上的文档

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

模板的数据上下文可用,则可以使用 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);