How to add a relationship or reference with AutoForm in Meteor?

1.8k views Asked by At

I use meteor-autoform to insert documents in a collection. My Items has a field groupId. How can I insert this group id when I'm submitting my item form.

<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>

I could create another field containing my group id but I don't want the user to see this field.

How can I set the groupId "behind the scenes"?

3

There are 3 answers

2
Kyll On

For that, you need a hook. Also you need to set an ID for the form, let's say 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
    }
  }
});
0
picsoung On

I think one solution is not this display this option to user. You need to also add optional:true to the field, so it will still be valid when you submit the form.

Then using the hooks, you should be able to add any other data you want

Doc is available hooks on autoform

I usually modify the doc on the before insert

AutoForm.hooks({
  myFormId: {
    before: {
      insert: function(doc, template) {
        //modify the document here
      }
    }
})
0
Matthias A. Eckhart On

You could use doc=this if the template's data context is available.

For example:

<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>

In further consequence, you could setup a hook which will be triggered before the insert operation:

var itemsHooks = {
    before: {
        insert: function (doc) {
            doc.groupId = this.currentDoc._id;
            return doc;
        }
    }
};

AutoForm.addHooks('insert-item-form', itemsHooks);