简体   繁体   English

如何在Meteor中使用AutoForm添加关系或引用?

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

I use meteor-autoform to insert documents in a collection. 我使用meteor-autoform将文档插入集合中。 My Items has a field groupId . 我的Items有一个字段groupId How can I insert this group id when I'm submitting my item form. 提交项目表单时,如何插入此组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>

I could create another field containing my group id but I don't want the user to see this field. 我可以创建另一个包含我的组ID的字段,但是我不希望用户看到此字段。

How can I set the groupId "behind the scenes"? 如何在“幕后”设置groupId

For that, you need a hook . 为此,您需要一个钩子 Also you need to set an ID for the form, let's say addItemForm . 另外,您需要为表单设置一个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
    }
  }
});

I think one solution is not this display this option to user. 我认为一种解决方案不是向用户显示此选项。 You need to also add optional:true to the field, so it will still be valid when you submit the form. 您还需要在字段中添加optional:true ,因此在您提交表单时它仍然有效。

Then using the hooks, you should be able to add any other data you want 然后使用钩子,您应该可以添加所需的任何其他数据

Doc is available hooks on autoform Doc可用于自动套用

I usually modify the doc on the before insert 我通常会before insert修改文档

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

You could use doc=this if the template's data context is available. 如果模板的数据上下文可用,则可以使用doc=this

For example: 例如:

<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>

In further consequence, you could setup a hook which will be triggered before the insert operation: 进一步的结果是,您可以设置一个在插入操作之前将被触发的钩子:

var itemsHooks = {
    before: {
        insert: function (doc) {
            doc.groupId = this.currentDoc._id;
            return doc;
        }
    }
};

AutoForm.addHooks('insert-item-form', itemsHooks);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM