DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Helper To Determine If Radio/checkbox Needs To Be Checked

09.07.2006
| 16782 views |
  • submit to reddit
        I frequently have to use methods such as 'radio_button' and 'check_box_tag' when I don't have an object with a method that will automatically determine the value of the input field.  Therefore, I have to check to see if a certain parameter has been passed, and if so, if the parameter's value matches that of the input's value.  This method does that.

It's designed to be used in a Rails helper.  You can either pass it the object, method, and value (the same parameters as, for example, <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M000395">radio_button</a>) or name and value (the same parameters as <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#M000501">radio_button_tag</a>).

def checked?( *args )
  if args.length == 3
    object, method, value = args
    if params[object] && params[object][method] && params[object][method] == value
      'checked'
    end
  elsif args.length == 2
    name, value = args
    if params[name] && params[name] == value
      true
    end
  end
end

Here's an example usage:
<%= radio_button 'person', 'age', '12', :checked => checked?( 'person', 'age', '12' ) %>

If params[:person][:age] exists and it equals '12', then 'checked?' returns 'checked'; otherwise, it returns nil.    

Comments

Snippets Manager replied on Fri, 2007/08/03 - 11:16am

I have a solution to this on my blog: http://www.freezzo.com Its one of the ones on there.

Snippets Manager replied on Thu, 2007/06/14 - 10:53pm

I tried this helper and I can't get it to work. Is anyone else using this successfully who coudl give me a hand??? Thanks, Sarah

Snippets Manager replied on Sun, 2007/01/21 - 7:37am

Ok, never mind - just added it into application_helper.rb

Snippets Manager replied on Sun, 2007/01/21 - 7:37am

Hi, Where would you add this code? Not on the model (I'm using it without a model using radio_button_tag), and it doesn't seem to work in the controller. Where should I place this? Thanks reinier