通过autoform钩子插入新文档调用流星方法
问题描述:
我想使用autoform将新文档插入到db中。 Autoform钩子在服务器上调用流星方法来插入文档。通过autoform钩子插入新文档调用流星方法
我有这个模板...
{{#autoForm collection="Reports" id="addReport" type="insert"}}
<div class="row">
<div class="col s6">
{{> afQuickField name='hours'}}
</div>
</div>
<button class="btn waves-effect waves-light modal-action modal-close"><i class="material-icons">save</i></button>
{{/autoForm}}
则...
AutoForm.hooks({
addReport: {
onSubmit: function(insertDoc) {
Meteor.call('addReport', insertDoc, function(error, result) {
if (error) alert(error.reason);
});
return false;
}
}
});
然后在服务器上的方法...
Meteor.methods({
addReport: function(insertDoc) {
var report = _.extend(insertDoc, {
userId: Meteor.userId(),
});
return Reports.insert(report);
}
});
我有一个createdAt
和updatedAt
集合中的字段,但它们都具有autoValue,因此我相信不需要插入fr om客户端或流星法。
所以收集与架构是这样的:
Reports = new Meteor.Collection('reports');
Reports.attachSchema(new SimpleSchema({
hours: {
type: Number,
label: "Number of hours",
decimal: true
},
createdAt: {
type: Date,
label: "Created Date",
autoValue: function() {
if (this.isInsert) {
return new Date;
} else {
this.unset();
}
},
denyUpdate: true
},
updatedAt: {
type: Date,
autoValue: function() {
if (this.isUpdate) {
return new Date()
}
},
denyInsert: true,
optional: true
},
"userId": {
type: String,
autoform: {
type: "hidden",
}
},
}));
当我运行流星,形式显示,而提交什么都不做。没有视觉提示如果有任何错误。在客户端和服务器控制台中都没有错误消息。
我在做什么错误或失踪?
答
aldeed /流星自动窗体文件:
// Called when form does not have a `type` attribute
onSubmit: function(insertDoc, updateDoc, currentDoc) {
Meteor.call()...
}
我下面discovermeteor的书,我想用这本书的一些方法,但使用流星自动窗体包。
post_submit.html
<template name="postSubmit">
{{#autoForm collection="Posts" id="insertPost"}} <-- no type
<div class="form-group">
<div class="controls">
{{> afQuickField name='title' class='title form-control'}}
</div>
</div>
<div class="form-group">
<div class="controls">
{{> afQuickField name='description' class='description form-control'}}
</div>
</div>
<input id="send" type="submit" value="Send" class="btn btn-primary"/>
{{/autoForm}}
</template>
post_submit.js
var postSubmitHook = {
onSubmit: function(insertDoc){
Meteor.call('postInsert', insertDoc, function(error, result) {
if (error){
Bert.alert(error.reason, 'danger', 'growl-top-right');
$('#send').removeAttr('disabled');
return;
}
Router.go('postPage', {_id: result._id});
});
return false;
}
};
AutoForm.addHooks('insertPost', postSubmitHook);
答
由于@Cristo GQ
这样做是正确的,我只是想确保答案是明确的足够该线程的未来游客
The onSubmit
hook会不惜一切
在另一方面使用仅为autoForms 与type='normal'
或没有任何type=
的before.insert
钩仅仅是type='insert'
而且没有before.normal
钩
这意味着当使用onSubmit
挂钩时,我们必须做任何“上班前”(如将当前用户添加到文档中)在onSubmit
本身内。
这是模式吗?它是否在模态之外工作? –
@AutumnLeonard nope。它不在一个模式。 – Rexford
嗯。我会一路添加一些控制台日志以查看正确调用的内容。 –