Search code examples
ruby-on-railsradio-buttonsimple-form

Custom IDs for input and label using Simple Form's radio buttons


I am creating multiple forms for the same resource in one page. Each of these forms has radio buttons.

However, Simple Form assigns the same ID to the same radio button options across all forms, causing a conflict.

How can I namespace each form, or select custom IDs for both each label and input?


Solution

  • If you use multiple simple_form_for methods in your view, they are just clever wrappers around the form_for built-in rails helper which supports the namespace option. Quoting from the form_for docs:

    :namespace - A namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

    So, something like the following should work:

    <%= simple_form_for @resource, namespace: "first_form" do |f| %>
    ...
    <% end %>
    
    
    <%= simple_form_for @resource, namespace: "second_form" do |f| %>
    ...
    <% end %>