2016-03-15 21 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