How to display search results from event in template

I’m creating the ability to search my players collection by last name. However, i don’t know how to pass the info to a helper to display it in my template from a submit event.

  • Should I set a session in the event and get & return it in a function within a helper?
  • Is there a way to pass the events returned variable to the template?
  • Should I use jquery.show method ( I feel like this would not be meteorish)
  • Is there a easy/better way?

Any help is appreciated in advance. Below is my event and template

Template.players.events({

"submit #search": function(event){
  event.preventDefault();
   //set variable to text/search box value
  var query = event.target.search.value;
   //get player where lastName contains search text box value. The i is for case insensative
  var players = players.find({"lastName": { $regex: ".*" + query + ".*", $options: 'i' } }).fetch();

return players;  
}
});//end player template event

My example Template( i’ve shortened it for ease of reading. The real one also includes the form for searching, etc…)

<template name="players">

 {{#each players}}
    {{firstName}} {{lastName}}
 {{/each}}

</template>

Okay. I think i figured this out. If anyone has a better way I would love to see it. The one thing that i’ve noticed in meteor is that there is a lot of bouncing around between functions/methods/helpers/events. I’m still learning but that is just my take.

I ended up using the session method and calling it in my helper.

Here is my helper, which I grabbed the session from my submit event. I used the if statement to show all players if my session wasn’t set.

Template.players.helpers({

    players: function () {
        //get the session from form submit event and set it to variable
      var query = Session.get('query');
        //set variable to get all players if search isn't used
      var allPlayers = players.find();
      
    //check if session has been set(only set by form submit event) if not show all players
      if(query){
        return players.find({"lastName": { $regex: ".*" + query + ".*", $options: 'i' } }).fetch();
      } else {
        return allPlayers;
      }

     },
});//end Template players helper

Here is my event where i set the session to the value of the search form input

Template.players.events({
  "submit #search": function(event){
    event.preventDefault();
     //set variable to get text/search box value
    var query = event.target.search.value;
     //set session on submit to search text box value
    Session.set('query', query);
  }
});//end player template event

My example Template( i’ve shortened it for ease of reading. The real one also includes the form for searching, etc…)

<template name="players">
 {{#each players}}
   {{firstName}} {{lastName}}
 {{/each}}
</template>
1 Like