<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: name code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Thu, 21 Aug 2008 06:47:28 GMT</pubDate>
    <description>DZone Snippets: name code</description>
    <item>
      <title>helper to determine if radio/checkbox needs to be checked</title>
      <link>http://snippets.dzone.com/posts/show/2559</link>
      <description>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.&lt;br /&gt;&lt;br /&gt;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, &lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M000395"&gt;radio_button&lt;/a&gt;) or name and value (the same parameters as &lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#M000501"&gt;radio_button_tag&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;&lt;code&gt;def checked?( *args )&lt;br /&gt;  if args.length == 3&lt;br /&gt;    object, method, value = args&lt;br /&gt;    if params[object] &amp;&amp; params[object][method] &amp;&amp; params[object][method] == value&lt;br /&gt;      'checked'&lt;br /&gt;    end&lt;br /&gt;  elsif args.length == 2&lt;br /&gt;    name, value = args&lt;br /&gt;    if params[name] &amp;&amp; params[name] == value&lt;br /&gt;      true&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Here's an example usage:&lt;br /&gt;&lt;code&gt;&lt;%= radio_button 'person', 'age', '12', :checked =&gt; checked?( 'person', 'age', '12' ) %&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;If params[:person][:age] exists and it equals '12', then 'checked?' returns 'checked'; otherwise, it returns nil.</description>
      <pubDate>Thu, 07 Sep 2006 16:25:27 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/2559</guid>
      <author>moneypenny ()</author>
    </item>
  </channel>
</rss>
