Search code examples
javascriptnode.jsmeteormeteor-autoform

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.


Solution

  • 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

    (e.g.)

    Template.instance().data.post._id


    This is a small sample for accessing data through templates

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