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:
-
<%= form_tag :action => 'create' %>
-
<%= text_field( "user_group", "name", "size" => 16 ) %>
-
<%= submit_tag " Cancel ", { :name => "user_group[Cancel]" } %>
-
<%= submit_tag " Save " %>
-
<%= 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:
-
def create
-
if !params[:user_group].include?( 'Cancel' )
-
@user_group = UserGroup.create( params[:user_group] )
-
end
-
-
redirect_to :action => 'list' and return
-
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”
Leave a Reply
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…