Rails: Cancel Buttons and Forms

Posted on January 19, 2007
Filed Under /dev/ruby | 759 views |

The Rails framework provides a great wealth of helper functions for creating forms via the FormHelper, FormTagHelper and FormOptionsHelper classes but one item conspicuously missing for some reason is a Cancel button.

Creating one is pretty straighforward, however. Lets say there's a form in place for creating new User groups:

RUBY:
  1. <%= form_tag :action => 'create' %>
  2. <%= text_field( "user_group", "name", "size" => 16 ) %>
  3. <%= submit_tag " Cancel ", { :name => "user_group[Cancel]" } %>
  4. <%= submit_tag " Save " %>
  5. <%= end_form_tag %>

To create a Cancel button I've used two instances of the submit_tag from FormTagHelper. Oddly the submit_tag doesn't take a 'name' parameter like most other form elements so to be able to differentiate between the Cancel and Save button I coerce Rails into giving the Cancel button the name I need it to have: :name => "user_group[Cancel]" (hard-coding seems a bit hackish to me but at the moment I lack a better solution).

To know which button has been clicked I add the following code to the UserGroupController:

RUBY:
  1. def create
  2.     if !params[:user_group].include?( 'Cancel' )
  3.       @user_group = UserGroup.create( params[:user_group] )
  4.     end
  5.    
  6.     redirect_to :action => 'list' and return
  7.   end

If the parameters from the form (as an array) contain a 'Cancel' element it skips the creation step and simply goes back to the list of existing user groups. If the parameters array does not contain a 'Cancel' element (ie 'Save' was clicked) it creates the new user group and then returns to the list of existing user groups.

Comments

One Response to “Rails: Cancel Buttons and Forms”

  1. Bill on March 14th, 2008 11:58 am

    I’ve noticed this works nicely on traditional forms, but when used in an RJS form, it won’t work. The Cancel button param will always be there. Bummer…

Leave a Reply