Search code examples
meteormeteor-autoform

meteorJS autoforms: Change a value before insert OR use multiple types of value


I use autoforms for my forms. Now I have a special problem and I am asking myself if its possible to solve this easy with autoforms.

With my autoforms I want to build a easy Category-Tree in my MongoDB. Just with a name and a parent (select).

This looks like this:

Categories.attachSchema(new SimpleSchema({
  name : {
    type: String,
    label: "Name",
    max: 200
  },
  parent : {
    type : String,
    allowedValues: [false, 'id_of_cat_1', 'id_of_cat_2', 'id_of_cat_3'],
    optional : true,
    autoform: {
      options: [
        {label: '- none -', value: false},
        {label: 'cat 1', value: 'id_of_cat_1'},
        {label: 'cat 2', value: 'id_of_cat_2'},
        {label: 'cat 3', value: 'id_of_cat_3'}

      ]
    }
  }
}));

Very short and very simple. The autoforms now creates me the form and I am able to do stuff with it.

But whats the problem here ? The problem is the parent-value. Its type is String and because of this selecting "- none -" is not possible. But I want that the field parent in the database has a boolean value (false) when no parent is given.

The question is now how to solve this.

Is it better - and possible - to give a value 2 or more types ? If not it must be necessery to overwrite the value after or before isnerting to the collection - but this also does not work because the simpleSchema do deny this process. FOr overwriting I use matb33:collection-hooks.


Solution

  • You can use empty string instead:

    parent : {
      type : String,
      allowedValues: ['', 'id_of_cat_1', 'id_of_cat_2', 'id_of_cat_3'],
      optional : true,
      autoform: {
        options: [
          {label: '- none -', value: ''},
          {label: 'cat 1', value: 'id_of_cat_1'},
          {label: 'cat 2', value: 'id_of_cat_2'},
          {label: 'cat 3', value: 'id_of_cat_3'}
        ]
      }
    }
    

    It makes sense since the empty string works as false in the if statement