Getting PostId for a comment using Autoform for Meteor
Without an auto-form, we usually do below to submit a comment:
comment-submit.js
'submit form': function(e, template) {
e.preventDefault();
var $body = $(e.target).find('[name=body]');
var status = {
body: $body.val(),
postId: template.data._id
};
We can inject a postId into each comment.
How can I do this with Autoform?
I tried this alongside the collection of comments:
Comments = new Mongo.Collection('comments');
Comments.before.insert(function (userId, doc) {
doc.postId = Posts.findOne()._id;
});
Comments.attachSchema(new SimpleSchema({
body: {
type: String,
autoform: {
'label-type': 'placeholder',
placeholder: 'Add your commentβ¦'
}
},
postId: {
type: String
}
}));
It works, but it always gets the postId of the 1st post in the collection, even it's actually the 2nd, 3rd, or other than the 1st post.
Please guide. Thank.
+3
source to share
1 answer
collection.findOne()
always returns the first document that was inserted into the collection. So the best way to do this that comes to my mind is through a hidden field. Just add the field to yourautoForm
{{ > afQuickField name="postId" value=_id style="display: hidden;" }}
This solution will work without any hooks or special attributes.
0
source to share