我使用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设置为“幕后”?
发布于 2014-12-17 18:05:37
为此,您需要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
}
}
});发布于 2014-12-17 18:09:32
我认为一种解决方案不是将这个选项显示给用户。您还需要将optional:true添加到该字段,以便在您提交表单时它仍然有效。
然后使用钩子,您应该能够添加任何其他您想要的数据
我通常在before insert上修改文档
AutoForm.hooks({
myFormId: {
before: {
insert: function(doc, template) {
//modify the document here
}
}
})发布于 2015-10-09 00:15:49
如果模板的数据上下文可用,则可以使用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);https://stackoverflow.com/questions/27522537
复制相似问题