Skip to content

Commit

Permalink
add ability to specify checked and uncked values for boolean input
Browse files Browse the repository at this point in the history
  • Loading branch information
nashby committed Sep 4, 2012
1 parent 46d4bb4 commit 9503f8e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/simple_form/inputs/boolean_input.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def label_input
# reuse the method for nested boolean style, but with no unchecked value,
# which won't generate the hidden checkbox. This is the default functionality
# in Rails > 3.2.1, and is backported in SimpleForm AV helpers.
def build_check_box(unchecked_value='0')
@builder.check_box(attribute_name, input_html_options, '1', unchecked_value)
def build_check_box(unchecked_value = unchecked_value)
@builder.check_box(attribute_name, input_html_options, checked_value, unchecked_value)
end

# Build a checkbox without generating the hidden field. See
Expand All @@ -49,7 +49,7 @@ def build_check_box_without_hidden_field
# we need the hidden field to be *outside* the label (otherwise it
# generates invalid html - html5 only).
def build_hidden_field_for_checkbox
@builder.hidden_field(attribute_name, :value => '0', :id => nil,
@builder.hidden_field(attribute_name, :value => unchecked_value, :id => nil,
:disabled => input_html_options[:disabled],
:name => input_html_options[:name])
end
Expand All @@ -65,6 +65,14 @@ def inline_label
def required_by_default?
false
end

def checked_value
options.fetch(:checked_value, '1')
end

def unchecked_value
options.fetch(:unchecked_value, '0')
end
end
end
end
18 changes: 18 additions & 0 deletions test/inputs/boolean_input_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,24 @@ class BooleanInputTest < ActionView::TestCase
assert_no_select 'label'
end

test 'input uses custom checked value' do
@user.action = 'on'
with_input_for @user, :action, :boolean, :checked_value => 'on', :unchecked_value => 'off'
assert_select 'input[type=checkbox][value=on][checked=checked]'
end

test 'input uses custom unchecked value' do
@user.action = 'off'
with_input_for @user, :action, :boolean, :checked_value => 'on', :unchecked_value => 'off'
assert_select 'input[type=checkbox][value=on]'
assert_no_select 'input[checked=checked][value=on]'
end

test 'input generates hidden input with custom unchecked value' do
with_input_for @user, :action, :boolean, :checked_value => 'on', :unchecked_value => 'off'
assert_select 'input[type=hidden][value=off]'
end

test 'input uses inline boolean style by default' do
with_input_for @user, :active, :boolean
assert_select 'input.boolean + label.boolean.optional'
Expand Down

0 comments on commit 9503f8e

Please sign in to comment.