【问题标题】:Conditional (category / subcategories) options in Meteor AutoFormMeteor AutoForm 中的条件(类别/子类别)选项
【发布时间】:2016-03-15 02:40:27
【问题描述】:

我目前正在使用 autoform 和 collection2 来生成表单。我想创建一个更改子类别选项的选择选项。

例如。选择(类别) - 水果 - 蔬菜

例如。选择(出现子类别)

如果选择了水果:

  • 苹果
  • 香蕉

如果选择蔬菜:

  • 胡萝卜
  • 西兰花

我一直在寻找解决方案,但找不到可行的解决方案。有人可以指出我正确的方向吗,因为我不确定从哪里开始。

【问题讨论】:

    标签: javascript meteor meteor-autoform meteor-collection2


    【解决方案1】:

    您可以使用 AutoForm.getFieldValue(fieldName, [formId]) 检索category 的当前值。然后,您可以set the subcategory options 取决于是否选择了fruitvegetables

    例如:

    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}));
                }
            }
        }
    }));
    

    【讨论】:

    • 嗨,马蒂亚斯,感谢您的建议。我正在尝试实现它,但是我得到了undefined for AutoForm.getFieldValue(fieldName, [formId])。表格是collection="Meteor.users'id="userProfile",所以我尝试了许多变体,但都没有运气。我在控制台中尝试的最后一个是AutoForm.getFieldValue(profile.category, [userProfile]); 知道我错过了什么吗?
    • @bp123 正如documentation 所述,函数参数必须作为字符串传递。因此,AutoForm.getFieldValue("profile.category", "userProfile"); 应该可以工作。
    • 好的,这是一种工作,除了子类别不会在选择时更新。我已经用我正在使用的模板将其重新定位,以查看是否可以快速修复。如果您能发现错误,请告诉我。谢谢马蒂亚斯,希望这会奏效。
    • @bp123 我已回复您的question
    • 像魅力一样工作。谢谢!
    猜你喜欢
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多