Self-Submitting Form Selects

   By chris on February 21st 2007 in /dev/rails | 297 views

After much scouring of the web and various Rails books I finally figured out how to generate a form select pop-up that self-submits to the page to update content (no Ajax in this... yet).

This goes into the view:

RUBY:
  1. <% form_for :user_group, :url => { :controller => :user_group,
  2.                                                    :action => :select } do |form| %>
  3. <%= form.select :id, UserGroup.find( :all, :order => 'name ASC' ).collect { |group| [ group.humanize_name( group.name ), group.id ] }, {}, :onchange => "selectGroup( this );" %>
  4. <% end %>

This is the javascript function that gets called when the form select is changed. Goes into the HTML page (or better, an included javascript file):

JAVASCRIPT:
  1. function selectGroup( $pSelect )
  2. { location.href = '?user_group_id=' + $pSelect.value; }

This goes into the controller. In my case the function called is "create", yours will probably differ:

RUBY:
  1. def create
  2.     # Check that the group value was passed in. If no value, select a default
  3.     params[:user_group_id] != nil ? user_group_id = params[: user_group_id] : user_group_id = 1
  4.  
  5.     # instantiate a group and store the selected id in it so that select item can be selected when next the page is generated
  6.     @user_group = UserGroup.new
  7.     @user_group.id =  user_group_id
  8.     ...
  9.     # rest of the logic here
  10.     ...
  11. end

Trackback URI | Comments RSS

Leave a Reply