Extending rails form helpers: a spinbox field
Spinboxes are common control in all desktop GUI applications. They’re found in all windowing toolkits that I know, and I use it all the time to input numbers. However, when it comes to web applications they are not so common. This is because (X)HTML doesn’t define such control.
I have found this great widget that requires prototype library only. It nicely degrades to text field when user doesn’t have javascript on, and is easy to use. However, I wanted to make it play nicely with Rails forms, to easily set up initial value etc.
Nothing easier. Just paste the following code to new file called lib/formhelperextensions.rb in you rails app:
module ActionView
module Helpers
module FormHelper
def spinbox_field(object_name, method, options = {})
min_val = options.delete(:min)
max_val = options.delete(:max)
tag = InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_input_field_tag("text", options.merge({:class =>"spin-button"}))
script = '<script type="text/javascript">new SpinButton($("'
script += "#{object_name}_#{method}"
script += '"),{'
script += "min:#{min_val}" if min_val
script += "," if min_val and max_val
script += "max:#{max_val}" if max_val
script += '});</script>'
tag+script
end
end
class FormBuilder
def spinbox_field(method, options = {})
@template.spinbox_field(@object_name, method, options)
end
end
end
end
and include the file at the end of your config/environment.rb
....
require "form_helper_extensions"Now, get a prototype-spin-button compressed archive, unpack it and copy spinbutton.js to your public/javascripts/ directory. Create file public/stylesheets/spinbutton.css and place following code in it:
input.spin-button {
padding-right:20px;
width:35px;
background-color:white;
background-repeat:no-repeat;
background-position:100% 0%;
background-image:url(/images/spinbtn_updn.gif);
}
input.spin-button.up {
cursor:pointer;
background-position:100% -18px;
}
input.spin-button.down {
cursor:pointer;
background-position:100% -36px;
}Last bit is to copy image spinbtn_updn.gif from zip archive to your public/images directory.
And, when you include spinbutton CSS and spinbutton.js in your view, you can use spinbutton in your forms! Your layout should have:
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag "spinbutton" %>
<%= stylesheet_link_tag "spinbutton" %>Use it in your forms, like you use text button:
form_for @user....
f.text_field :name
f.spinbox_field :age, :min => 0, :max => 120
endEnjoy!