Monday, August 13, 2007

Back to Search Results

So today I encountered a problem that I seem to encounter in every web application I develop. Most web applications require a search and a way to view each results details. When you view the details you most of the time want to go back to your search results and not have to re-enter all of the fields of your search form.

There are a few ways to do this.

First you can use the quick and dirty way that will not work all the time.

input value="Go" onclick="history.go(-1)" type="button"

The javascript function history.go is very useful if the client has javascript enabled. If they do not have javascript enabled this button will do absolutely nothing and frustrate your user beyond all means

The second option is to use the server to store the search params

# staff_controller.rb
def view_applications
if params[:type] == "requery"
search_params = session[:search_params]
search_params = params
session[:search_params] = params
@applications = Staff.find_applications_by_params(search_params)

As you can see when the view_applications method is called the params are checked for a variable called type, if this is being called from the original search that field would be empty and the else portion kicks in causing the params to be stored in session. Below you will see the link_to example from the page that shows the details of a record. You will notice that the params have a type that is set to requery, which triggers the function to use the params from session to display the results.

link_to "<< Back to Search Results", :action => :view_applications, :type => "requery"

There you have it, a way in rails to use the search results from before. If you have any other ways of doing this please post a comment.


No comments: