2016-03-15 41 views
0

我目前使用autoform和collection2来生成表单。我想创建一个选择选项来更改子类别选项。Meteor AutoForm中的条件(类别/子类别)选项

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

如。选择(出现子类)

果果选择:

  • 苹果
  • 香蕉

如果选择蔬菜:

  • 胡萝卜
  • 西兰花

我一直在寻找一个解决方案,但我不能找到一个工程。有人可以请我指出正确的方向,因为我不知道从哪里开始。

回答

1

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

例如:

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

喜马蒂亚斯,感谢您的建议。我试图实现它,但是我得到'未定义'AutoForm.getFieldValue(fieldName,[formId])'。形式是'collection =“Meteor.users''' =”userProfile“'所以我尝试了许多变化,没有运气。我在控制台中尝试的最后一个是'AutoForm.getFieldValue(profile.category, [userProfile]);'任何想法我失踪? – bp123

+0

@ bp123作为[文档](https://github.com/aldeed/meteor-autoform/blob/master/api.md#autoformgetfieldvaluefieldname-formidclient)国家,函数参数必须作为字符串传递,因此,'AutoForm.getFieldValue(“profile.category”,“userProfile”);'应该工作 –

+0

好吧,这是一种工作,除了子类别不更新选择。如果你能发现错误,请告诉我,谢谢Matthias希望这能起作用 – bp123