选择类别不更新子类别

时间:2016-03-18 01:06:37

标签: javascript meteor meteor-autoform meteor-collection2

这是假设查看用户类别选择,然后更新子类别。该解决方案是由其他人推荐的,但我似乎无法让它工作。当我选择类别时,子类别不会更新。有人能让我知道我错过了什么。

路径:category.js

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

路径: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 个答案:

答案 0 :(得分:2)

在浏览器的控制台日志中调用AutoForm.getFormValues('categoryForm');时,将返回以下结果:

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

从上面可以看出,架构字段subcategory被引用为profile.categories.subcategory。因此,字段subcategory将不会更新,因为AutoForm.getFieldValue("category");会返回undefined

您可以通过更改

来修复此错误
let category = AutoForm.getFieldValue("category"); 

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

options架构字段中的subcategory函数内。