Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependent select box meteor

Tags:

meteor

I'm trying to wrap my head around the meteor dependencies and reactive variables. I have two select boxes. One lists a category (fruit, vegetables, poultry, etc) the second will list the sub category (apples, pears, grapes, etc).

I'd like when the user changes the category dropdown to display and populate the subcategory dropdown.

I know I can watch for Template.action_form.events ={'change #category'}... but I'm not sure what steps to take from here. One thought (hack) is to output all the subcategories to a multidimensional array and use jquery to manage it. I have to think there is a smarter way to to do this with meteor.

for the category dropdown I have something like this:

Template.action_form.category = function(id){
    return Category.find();
}

I'm not sure how to setup the template for the subcategory...right now I have this (not working)

Template.action_form.subcategory = function(parent){
  if (document.getElementById(parent)){
      category = document.getElementById(parent).value;
      return Subcategories.find({category_id:parent}); 
  }
}

The HTML/Template looks like this:

<template name="action_form">
    <select id="category" class="action-selects">
        {{#each category _id}}
        <option value="{{_id}}">{{name}}</option>
        {{/each}}
    </select>
    <select id="subcategory" class="action-selects">
        {{#each subcategory "category"}}
        <option value="{{_id}}">{{name}}</option>
        {{/each}}
    </select>
<template>

Thanks in for any pointers you all can offer.

like image 768
Joshc Avatar asked Aug 13 '26 01:08

Joshc


1 Answers

if you want to use the whole reactivity magic of meteor for this, you could set an Session variable if the first select changes.

Template.action_form.events = {
  'change #category': function(evt) {
     Session.set("selected_category", evt.currentTarget.value);
  }
}

Your subscription of Subcategories passes the selected category as a parameter into the servers publish method.

// Client
Meteor.autosubscribe(function () {
  Meteor.subscribe("subcategories",Session.get("selected_category"));
}

// Server
Meteor.publish("subcategories", function(selectedCategory) {
  Subcategories.find({category_id: selectedCategory})  
});

The template for subcategories than displays all Subcategories if finds.

Template.action_form.subcategory = function(parent){
  Subcategories.find();
};

You could, of course, publish all Subcategories at once (no idea how many you'll have there) and filter the subcategories in the client, not in the subscribe/publish methods.

Template.action_form.subcategory = function(parent){
  Subcategories.find({category_id: Session.get("selected_category")});
};
like image 70
Andreas Avatar answered Aug 14 '26 19:08

Andreas