I need to read values from a MongoDB Collection and then check (or not) the checkboxes in a Meteor Template based on a field in the Document which matches the value of a checkbox.
To take a step back first, I populate the Template with the checkboxes like so:
<div id="seljoblocs" name="seljoblocs">
{{#each jobLocs}}
<input type="checkbox" value={{jl_jobloc}}><label>{{jl_jobloc}}</label>
{{/each}}
</div>
...populating the value and the label from the Template's "jobLocs" Helper:
jobLocs: function() {
return JobLocations.find({}, {
sort: {
jl_jobloc: 1
},
fields: {
jl_jobloc: 1
}
});
}
When a selection is made from a "worker" input select element, I can note which worker was selected like so:
Template.matchWorkersWithJobLocs.events({
'change #selworker': function(event, template) {
var workerid = template.find('#selworker').value;
// TODO: Add code to query Collection and then check the appropriate checkboxes
},
...so that I can check the checkboxes where matches are found (a "match" means that the worker is qualified to be assigned to the job/location). IOW, with the returned Document field value (jobloc), I want to check the appropriate checkboxes.
My question is, how I can do that?
Is it the case (hopefully!) that, within the following SpaceBars loop:
{{#each jobLocs}}
<input type="checkbox" value={{jl_jobloc}}><label>{{jl_jobloc}}</label>
{{/each}}
...I can have an "isChecked" helper like this:
{{#each jobLocs}}
<input type="checkbox" value={{jl_jobloc}} {{isChecked}}><label>{{jl_jobloc}}</label>
{{/each}}
...that either returns an empty string or the string "checked" based on whether this Meteor method returns true:
Template.matchWorkersWithJobLocs.helpers({
isChecked: function () {
var workerid = $('#selworker').val;
if (null == WorkersJobLocsLookup.findOne( {wjllu_workerid: workerid, wjllu_jobloc: jobLocs.jl_jobloc})) {
return '';
} else {
return 'checked';
}
}
That way, the checkbox will be checked (because the function returns "checked", which checks the checkbox) or not, because the function returns an empty string.
IOW, to get to the nitty gritty, is the "jobLocs.jl_jobloc" field from the Spacebars loop available/accessible within the helper, so that I can see if it has a corresponding Document in the WorkersJobLocsLookup Collection?
Not sure I'm exactly sure what you're asking, but you can access the values of items in the current row / handlebars iteration in a helper with this._id
or this.someField
Possibly something like this if I am reading you correctly:
Template.matchWorkersWithJobLocs.helpers({
getJobsLocs: function() {
var job = this.jobLocs.jl_jobloc;
return WorkersJobLocsLookup.findOne({
fieldWithJobLoc: job
});
}
});
If you are trying to return more than one result, use find
, not findOne
, and you may want to put it inside an if (Template.instance().subscriptionsReady()) {}
function.