simple_form renders radio buttons incorrectly

与世无争的帅哥 提交于 2019-12-01 11:58:19

Here is a better solution than my original below.

From the code:

#   form_for @user do |f|
#     f.collection_radio_buttons(
#       :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
#     ) do |b|
#       b.label { b.radio_button + b.text }
#     end
#   end

I think this is what you are looking for:

<%= f.collection_radio_buttons(
    :gender, [['Male', 'Male'], ['Male', 'Male']], :first, :last
  ) do |b|
    b.label { b.text + b.radio_button }
  end
%>

You can even add other helpers like image_tag in there too:

<%= f.collection_radio_buttons(
    :gender, [['Male', 'Male'], ['Male', 'Male']], :first, :last
  ) do |b|
    b.label { image_tag("#{b.text}.png") + b.radio_button }
  end
%>

This solution is not a normal custom component. This custom compontent inherits from CollectRadioButtonsInput instead of the normal CollectionInput class. I modified the 2 relevant methods.

Inside app/inputs/radio_buttons_left_label_input.rb

class RadioButtonsLeftLabelInput < SimpleForm::Inputs::CollectionRadioButtonsInput
  def input
    label_method, value_method = detect_collection_methods

    @builder.send("collection_radio_buttons",
      attribute_name, collection, value_method, label_method,
      input_options, input_html_options, &collection_block_for_nested_boolean_style
    )
  end

  protected

  def build_nested_boolean_style_item_tag(collection_builder)
    collection_builder.text.html_safe + collection_builder.radio_button.html_safe
  end
end

It can be used like this

<%= form.input :gender,
  :as => :radio_buttons_left_label,
  :collection => %w[Female Male]
%>

Not sure of the exact thing, but there is something called order which can be assigned which tag to be displayed first e.g. [:label, :input] and also inlining may help here.

Have you tried to simply create or sort the collection in the order which you want?

Somethink like this :

= f.input :gender,
    :collection => gender.reverse,
    :as => :radio_buttons,
    :item_wrapper_class => 'inline'

Obviously, this is not the better solution. You should create the list in the right order.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!