0
votes

I'am trying to implement 2 selects in a template. One is for selecting a single category from all of Categories collection, and the other is for selecting a set of skills related to that particular category. So, the latter is dependent on the first. What I think is the right way of doing that is to have a session variable to store selected category id upon select change event and helper function that reactively return cursor with that id. My code looks like...

<template name="createPost">
    <select id="categories" name="category">
        {{#each categories}}
            <option value="{{_id}}">{{categoryName}}</option>
        {{/each}}
    </select>
    ...
    <select id="skills" name="skills">
        {{#each skills}}
            <option value="{{_id}}">{{skillName}}</option>
        {{/each}}
    </select>
</template>

Template.createPost.helpers
    categories: -> Categories.find()
    getCategory = ->
        Session.get 'selectedCategory'
    Tracker.autorun ->
        skills: ->
            Skills.find {category: getCategory}

Template.createPost.events
    "change #categories": (e) ->
        Session.set 'selectedCategory', e.target.value
    ...........

First select is populated with categories. However, when I choose a category, related skills are not shown in the second select. Any idea what's wrong with this code, sorry I am still pretty new to meteor. Thanks in advance.

1
have you tried this without the tracker.autorun? - challett
yes I tried it without tracker.autorun. I also tried to put the second select in a separate template and its own helper, still no luck - Zaya
So for clarification, are no skills showing up or are they all showing up? Can you post an example category and skill? Also, what are the results of Skills.find({}) in the console after selecting a category? - challett
no skills showing up. I have a category called NodeJS and 2 skills MeteorJS and HTML5, each has category field with the id of NodeJS. - Zaya
Are you using the insecure package? If not what does your subscription/publication look like? - challett

1 Answers

1
votes
Template.createPost.helper
  categories: () ->
    Categories.find()
  skills: () ->
    selectedCategory = Session.get 'selectedCategory'
    Skills.find {category: selectedCategory}

Template.createPost.events
  "change #categories": () ->
    Session.set 'selectedCategory', $('#categories').val()

Template.createPost.onRendered () ->
  this.autorun () ->
    c = Categories.find().fetch()[0]
    if c
      Session.set 'selectedCategory', c._id