Meteor - autoform - Coercing data

meteor-autoform

See "Converting data before it goes into the form" from http://www.webtempest.com/meteor-js-autoform-tutorial

When should we use formToDoc, formToModifier, and docToForm?

Specify formToDoc, formToModifier and docToForm hooks if you need form values in a different format in your form versus in the mongo document. They are mainly useful if you decide to override an input type.

Unlike document modifications made in "before hooks", modifications made in the formToDoc hooks are made every time the form is validated, which could happen a couple times per second on the client, depending on validation mode. The other hooks are run only right before the corresponding submission actions, as their names imply.

Here is an example where this feature is used to allow comma-delimited entry in a text field but store (and validate) the values as an array:

First specify type: [String] in the schema. The schema should reflect what you are actually storing. Add a type attribute to your afFieldInput component:

{{> afFieldInput name="tags" type="text"}}

Then in client code, add the hooks:

AutoForm.hooks({
  postsForm: {
    docToForm: function(doc) {
      if (_.isArray(doc.tags)) {
        doc.tags = doc.tags.join(", ");
      }
      return doc;
    },
    formToDoc: function(doc) {
      if (typeof doc.tags === "string") {
        doc.tags = doc.tags.split(",");
      }
      return doc;
    }
  }
});

Note that the update and method-update forms call formToModifier instead of formToDoc, and forms without a type attribute call both formToModifier and formToDoc. formToModifier is passed a Mongo modifier instead of a document.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License