lost password?

home
•  reviewramp
•  rails +
•  javascript
•  webdev
•  django
•  xaraya
•  xamp
•  musings

rss
Tag this page
   

» Blogs that link here
last modified: Feb 27, 2009
(first posted: Feb 27, 2009)
(961 Reads)
keywords: helpers
Permalink

button_submit_tag

A helper that's been missing from Rails

With submit_tag to submit forms, the action receives params[:commit] => value of the button, where value is also the label on the button. That's been fine most of the time even when you decide to change the button label from, for example, "Update" to "Save Changes", since, most of the time you don't care at all about that. But when a form has more than one way to submit you may need to know which of the buttons were clicked. In that case the controller might have hardcoded the :commit value, eg if params[:commit] == 'add' etc. Then tying the value to the GUI can make you scream, especially in cases where there's multiple buttons.

The solution would be to use the <button> tag, but for some reason Rails doesn't have a button_submit_tag helper. (Anyone know why?)

So with some tinkering I got a helper that works; throw it into application_helper.rb:

  def button_submit_tag(name, value=nil, label=nil, options = {})
    content_tag :button, label||name.humanize, 
{ "type" => "submit", "name" => name, "id" => name,
"value" => value||name }.update(options.stringify_keys)
  end

You can use it like,

<%= button_submit_tag( 'add_item', 'foo', 'Add a Foo',  :title => 'Add an item' ) %>

results in

<button value="foo" type="submit" title="Add an item" name="add_item" id="add_column">Add a Foo</button> 

and submits

params[:add_item] => 'foo'

Label could be any html (but if just an image, might as well use image_submit_tag helper). I probably should extend it to accept a content block also, but it works fine as is for me right now.

There are no comments attached to this item.

Post a new comment

How many days in a week?

Name :