Search code examples
javascriptmeteormeteor-autoformmeteor-collection2

Conditional (category / subcategories) options in Meteor AutoForm


I'm currently using autoform and collection2 to generate forms. I would like to create a select option that changes the sub category options.

eg. Select (category) - fruit - vegetables

eg. Select (sub-category appears)

If fruit selected:

  • apples
  • banana

If vegetables selected:

  • carrot
  • broccoli

I've been searching for a solution but I can't find one that works. Can someone please point me in the right direction as I'm not sure where to start.


Solution

  • You could retrieve the current value of category by using AutoForm.getFieldValue(fieldName, [formId]). Then, you could set the subcategory options depending on whether fruit or vegetables has been selected.

    For example:

    var fruitArr = ['apple', 'banana'];
    var vegetablesArr = ['carrot', 'broccoli'];
    
    Food = new Mongo.Collection("food");
    
    Food.attachSchema(new SimpleSchema({
        category: {
            type: String,
            label: "Category",
            allowedValues: ['fruit', 'vegetables']
        },
        subcategory: {
            type: String,
            label: "Subcategory",
            allowedValues: _.union(fruitArr, vegetablesArr),
            autoform: {
                options: function () {
                    let category = AutoForm.getFieldValue("category");
                    if (!category) return [{label: "Please select a category first", value: ""}];
                    if (category === "fruit") return _.map(fruitArr, (v, i) => ({
                        label: "Fruit " + (i + 1) + ": " + v,
                        value: v
                    }));
                    else return _.map(vegetablesArr, (v, i) => ({label: "Vegetables " + (i + 1) + ": " + v, value: v}));
                }
            }
        }
    }));