Simple_form: Specifiying checked and unchecked value for checkboxes

Created on 13 Aug 2012  路  10Comments  路  Source: heartcombo/simple_form

The Rails form builder allows one to specify the checked and unchecked values for checkboxes. It appears SimpleForm doesn't allow this and defaults to 1 for checked and 0 for unchecked. Is there any way to specify a checked value of true and unchecked value for false in SimpleForm?

I need this because my attributes are within a postgresql hstore and all values are strings.

Most helpful comment

@barelyknown that should be:

f.input :my_boolean, input_html: { checked: @object.my_boolean }

Checked in stead of check.

All 10 comments

Yeah, SimpleForm does default to 1/0, and there's no way to change it currently. You could use the block version as a workaround, though, with something like:

f.input :my_boolean, as: :boolean do
  f.check_box :my_boolean, {}, "true", "false"
end

That should work for your particular use case. We may add the options :checked_value/:unchecked_value to the input itself, not sure yet, I'll leave it open to get more feedback. Thanks!

You asked for feedback, so I for one would love to see this feature being pulled into the next release.

@Axsuul @hydrat hey guys, you can try this feature from master branch!

@nashby Works for me. Thank you very much for your quick reaction.

Any ideas when you will release a new version of the gem so I can use this in production as well?

@hydrat not sure actually. We should ask @rafaelfranca or @carlosantoniodasilva this question. :)

Hey guys, you can hopefully expect a new release soon. There's a lot of bug fixes and some cool stuff in master already, most from @nashby's work :). It's just that we haven't had much time lately to clean everything up for a release, but I hope to be able to do that soon enough. Cheers!

I came across a simple solution on StackOverflow that works fine.

f.input :my_boolean, input_html: { check: @object.my_boolean }

@barelyknown that should be:

f.input :my_boolean, input_html: { checked: @object.my_boolean }

Checked in stead of check.

@webdevotion thank you:)))

Now after PR merge, it's simple as:
f.input_field :shift_option, as: :boolean, checked_value: 'warning', unchecked_value: 'open'

Was this page helpful?
0 / 5 - 0 ratings