简体   繁体   中英

Add postId to comments with autoform in Meteor

How can I link add postId to comments when using meteor-autoform ?

I have tried

AutoForm.hooks({
  insertCommentForm: {
    formToDoc: function(doc) {
      doc.postId = this.formAttributes.parentContext._id;
      return doc;
    },
  }
});

and

AutoForm.hooks({
  insertCommentForm: {
    formToDoc: function(doc) {
      doc.postId = Template.parentData(1)._id;
      return doc;
    },
  }
});

and

AutoForm.hooks({
  insertCommentForm: {
    before: {
      method: function(doc) {
        doc.postId = this.formAttributes.parentContext._id;
        return doc;
      }
    }
  }
});

and

AutoForm.hooks({
  insertCommentForm: {
    before: {
      method: function(doc) {
        doc.postId = Template.parentData(1)._id;
        return doc;
      }
    }
  }
});

but postId is undefined no matter what I do.

Edit

I use it like this:

<template name="comment">
  <div>
    <h1>{{_id}} {{title}}</h1>
    {{#if currentUser}}
      {{> quickForm collection="Comments" id="insertCommentForm" type="insert"}}
    {{/if}}
    ....

so _id should be accessible.

Edit 2

Now I have tried

before: {
  insert: function(doc, template) {
    doc.postId = Template.instance().post._id;
    console.log(doc);
    return doc;
  }
},

and in the template I use

{{> quickForm collection="Comments" id="insertCommentForm" type="insert" post=this template="bootstrap3-inline" label-class="sr-only"}}

but post is undefined so I get the error Uncaught TypeError: Cannot read property '_id' of undefined .

Instead using your

{{> quickForm collection="Comments" id="insertCommentForm" type="insert"}}

just try

{{> quickForm collection="Comments" id="insertCommentForm" type="insert" postId=_id}}

and then try to access this value inside the helper via

Template.instance().data.postId


You also can send the whole post object to the sub-template like

{{> quickForm collection="Comments" id="insertCommentForm" type="insert" post=this}}

and then have full access to that collection document via

(eg)

Template.instance().data.post._id


This is a small sample for accessing data through templates

http://meteorpad.com/pad/Ke9DJnbvtsqjSHJy2/SimpleDataGivenThroughTemplates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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