Reputation: 99
Is there a canonical way to populate a select control in Meteor and set the control to the existing value in the underlying data? I have already found a way to populate the "options" in the select control. What I still need to do is created the options so that the correct option is selected to match the already existing data.
It seems most meteor examples imagine fairly simple forms. I have to deal with business data. I may have a record, which has child records... say contact emails.... so each line for a contact email has a select for "email type". Imagine there are 2 contact email records...when I display them i need to set the "selected" value for the correct option. but the only examples I find for this use session variables ??? to store the selected values... so they can be referenced inside the template that is laying out the select.
Use #with seems to have only one level... that is, I can't #with inside of an already existing #with
Upvotes: 2
Views: 241
Reputation: 1437
The selected element needs to have this attribute:
selected="selected"
(or some variant - just selected works fine)
To conditionally include it, make a template helper (called isSelected for example) that return true/false based on your logic. Your html loop for options will look like this:
<option value = "{{value}}" {{#if isSelected}} selected="selected" {{/if}} >
{{description}}</option>
As a refinement, rather than a helper, you could add a true/false field named isSelected to each record. The template won't care whether it's a field or a helper.
For "Use #with seems to have only one level... that is, I can't #with inside of an already existing #with"
I have taken to fixing up the inner object with a reference to the outer, so both are accessible in the nested with. For example, to associate any/all of one collection with a document, I prep the data:
Handlebars.registerHelper 'allSureties', (document) ->
included = document.sureties or [] # the array that tracks ids for surety recs that this doc has
_.map _sureties, (sure) ->
sure.owner = document
sure.isContained = sure._id in included
sure.vents = "agent:sureties:#{document._id}:#{sure._id}" # see you can get both IDs this way
sure
and then my template uses that this way (notice you can access owner._id):
{{#each allSureties this}}
{{switch value=value
fname=nickname
group="sureties"
on=nickname
off=nickname
object=owner._id
vents=vents
_id=_id }}
{{/each}}
Hope this helps.
Upvotes: 0