Changeset 923

Show
Ignore:
Timestamp:
11/09/07 22:18:29 (1 year ago)
Author:
jimfree..@gmail.com
Message:

Updated checkbox to take :on and :off attributes. Defaults to "1" and "0" respectively. Also adds a hidden field so the :off state will return a value from the browser.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • plugins/merb_helpers/lib/form_helpers.rb

    r920 r923  
    7777      end 
    7878       
     79      def cb_val_to_bool(val) 
     80        !(val == false || val.nil?) && val.to_i != 0 
     81      end 
     82      private :cb_val_to_bool 
     83 
    7984      def checkbox_control(col, attrs = {}) 
    8085        errorify_field(attrs, col) 
    81         val = @_obj.send(col) 
    82         attrs.merge!(:value => val ? "1" : "0") 
    83         attrs.merge!(:checked => "checked") if val 
     86        attrs.merge!(:checked => "checked") if cb_val_to_bool(@_obj.send(col)) 
    8487        checkbox_field(control_name_value(col, attrs)) 
    8588      end 
    86        
     89 
    8790      def checkbox_field(attrs = {}) 
     91        on            = attrs.delete(:on)  || 1 
     92        off           = attrs.delete(:off) || 0 
     93        attrs[:value] = on if (!attrs.has_key?(:value) || attrs[:value].nil?) 
    8894        attrs.merge!(:type => :checkbox) 
    8995        attrs.add_html_class!("checkbox") 
    90         optional_label(attrs){self_closing_tag("input", attrs)} 
     96        hidden_field(:name => attrs[:name], :value => off) + optional_label(attrs){self_closing_tag("input", attrs)} 
    9197      end 
    9298       
  • plugins/merb_helpers/specs/merb_helpers_spec.rb

    r758 r923  
    216216  end 
    217217   
     218  it "should allow a user to set the :off value" do 
     219    form_for :obj do 
     220      checkbox_control(:baz, :off => "off", :on => "on").should match_tag(:input, :type =>"checkbox", :name => "fake_model[baz]", :class => "checkbox", :value => "on", :checked => "checked") 
     221      checkbox_control(:bat, :off => "off", :on => "on").should match_tag(:input, :type =>"checkbox", :name => "fake_model[bat]", :class => "checkbox", :value => "off") 
     222    end 
     223  end 
     224   
    218225  it "should render controls with errors if their attribute contains an error" do 
    219226    form_for :obj do