x-govuk/govuk-form-builder

Not able to check a govuk_radio_button value

Closed this issue ยท 5 comments

I'm using the govuk_radio_button on an edit page. It contains the nested attribute values for the model. I'd want to check the current selected value on a condition, but I can't find an attribute that works. I've tried with checked, but it seems it doesn't exist. Looked through the codebase and documentation and couldn't find anything. Is it not possible? Thanks.

Yeah - it's definitely possible to set the checked option. I'd recommend setting the attribute on the model in the controller (or defaulting it to something) rather than in the view via an argument, though.

Here's a quick example:

  # orders_controller.rb
  def new
    @order = Order.new
    @order.extra_topping_id = 2
  end
  <%= form.govuk_radio_buttons_fieldset(:extra_topping_id, legend: { text: "Select your toppings" }) do %>
    <%= form.govuk_radio_button(:extra_topping_id, 1, label: { text: "Ham" }) %>
    <%= form.govuk_radio_button(:extra_topping_id, 2, label: { text: "Pineapple ๐Ÿ" }) %>
    <%= form.govuk_radio_button(:extra_topping_id, 3, label: { text: "Sweetcorn" }) %>
  <% end %>

Result:

Screenshot from 2021-05-04 15-41-57

Alternatively, you should be able to just pass checked: true, like this:

  <%= form.govuk_radio_button(:extra_topping_id, 2, checked: true, label: { text: "Pineapple ๐Ÿ" }) %>

I tested locally and it's working for me.

Thanks for your reply. Setting it in the controller is a bit tricky, because of the nested attributes. I'll look into it, maybe using a transient attribute. Unfortunately, the checked option doesn't seem to be available in the version I'm using: 1.2.0b1

Ah, yeah - since then the way extra args/keyword args are dealt with internally has been overhauled and standardised. I'd recommend upgrading, there aren't too many breaking changes (and those that do are straightforward to fix). There's details on them in the changelog. I can assist if you hit any problems.

Going to close this as I think it's solved by moving to the latest version, happy to re-open if you need any assistance @vassyz

Hi @peteryates , sorry for not replying quicker. Unfortunately, we are not able to upgrade the gem at this point in time. I tried doing it quickly, for testing purposes, and I got errors related to hint_text and the styling was a bit off. It will require some effort and it is not out biggest priority at the moment. Thank you again for your help!