x-govuk/govuk-form-builder

Single checkbox has suprising behaviour

Closed this issue · 2 comments

Related to: DFE-Digital/apply-for-teacher-training#3237 (comment)

We've built a couple of forms that look like this:

<%= form_with model: @user do |f| %>
  <%= f.govuk_check_box :admin, true %>
  <%= f.govuk_submit 'Save' %>
<% end %>

A form like this will submit params[:user][:admin] == "true" - a string, not a boolean.

Then, when you assign this value like @user.admin = params[:user][:admin] and render the form again, your checkbox will be unchecked, because it compares "true" to true.

<%= form_with model: User.new(admin: "true") do |f| %>
  <%= f.govuk_check_box :admin, true %>
  <%= f.govuk_submit 'Save' %>
<% end %>

Setting the govuk_check_box value to any other value will work - even nil because the value will be "on".

<%= form_with model: User.new(admin: "on") do |f| %>
  <%= f.govuk_check_box :admin, nil %>
  <%= f.govuk_submit 'Save' %>
<% end %>

I think we could compare the stringified version of the value to make this work out of the box? Otherwise, would raising an error be good?

Thanks for reporting this @tijmenb. It's bitten a few people and is something that definitely needs attention. As a result of a similar query a while ago I changed the guide entry for single checkboxes to use a 1 and 0. I believe that setup should just work for single checkboxes.

Setting an unchecked value is important because otherwise it defaults to false which causes Rails not to generate a hidden field for when the checkbox is unchecked; the fieldset also needs to be informed (via multiple: false) because for multiple checkboxes it has the responsibility of generating the hidden field.

It's a bit of a headache, the docs can definitely be made clearer here though. If there's a silver bullet code fix I'd welcome the PR 😄

I think this is covered by the example in the guide, I've also added a link from the intro paragraph directly to the example to hopefully make it clearer. Willing to reopen and try to make it more intuitive if necessary but will close for the moment. Thanks.