add ability to specify checked and uncked values for boolean input

closes #643
This commit is contained in:
Vasiliy Ermolovich 2012-08-26 15:06:19 +03:00
parent 46d4bb406b
commit 9503f8e6a4
2 changed files with 29 additions and 3 deletions

View File

@ -34,8 +34,8 @@ module SimpleForm
# 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
@ -49,7 +49,7 @@ module SimpleForm
# 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
@ -65,6 +65,14 @@ module SimpleForm
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

View File

@ -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'