Select category not updating sub category

2019-09-02 04:09发布

问题:

This is suppose to look at the users category selection and then update the subcategory. The solution was recommended by someone else but I can't seem to get it to work. When I select the category, subcategory doesn't update. Can someone let me know what I'm missing.

Path: category.js

<template name="category">
    {{#autoForm collection="Meteor.users" id="categoryForm" doc=currentUser type="update"}}
        {{> afQuickField name='profile.categories'}}
    {{/autoForm}}   
</template>

Path: Schema.js

var fruitArr = ['apple', 'banana'];
var vegetablesArr = ['carrot', 'broccoli'];

Schema.Category = 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}));
            }
        }
    }
});

Schema.UserProfile = new SimpleSchema({
    categories: {
        type: Schema.Category,
        optional: true,
    }
});

回答1:

When calling AutoForm.getFormValues('categoryForm'); in the browser's console log, the following result will be returned:

{
   "insertDoc":{
      "profile":{
         "categories":{
            "category":"fruit"
         }
      }
   },
   "updateDoc":{
      "$set":{
         "profile.categories.category":"fruit"
      },
      "$unset":{
         "profile.categories.subcategory":""
      }
   }
}

As you can see from above, the schema field subcategory is referenced as profile.categories.subcategory. Therefore, the field subcategory won't be updated because AutoForm.getFieldValue("category"); returns undefined.

You can fix this error by changing

let category = AutoForm.getFieldValue("category"); 

to

let category = AutoForm.getFieldValue("profile.categories.category");

inside your options function in the subcategory schema field.