How do you add a tag before each radio button in Simple Form?
Asked Answered
S

0

1

Simple necessity, but clearly no easy way to do it with Simple Form.

I need to put a span before each radio input in a Rails form that uses Simple form. I've successfully added a span to a text input as stated in this guidelines, but I cannot make out how to do the same thing with radio buttons (as well as check boxes).

I don't want to use jQuery, which I am currently using as a workaround.


UPDATE 1

As @TarynEast asked in a comment, I tried creating an initializer with the following code I've been able to prepend a span tag to a string input.

Initializer

# config/initializers/simple_form__spanner
class SpannerInput < SimpleForm::Inputs::Base
  def input(wrapper_options)
    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)

    spanner_input = "<span></span>"
    spanner_input << @builder.text_field(attribute_name,merged_input_options)
    return spanner_input.html_safe
  end
end

View

# the view code
<%= ff.input :xxx, label: 'XXX', as: :spanner %>

HTML Output

# the output in view
<div class="form-group spanner optional xxx">
  <div class="control-label-wrap">
    <label class="control-label spanner optional" for="xxx_1">XXX</label>
  </div>
  <span></span> 
  <input class="form-control spanner optional" type="text" value="some value" name="xxx[1]" id="xxx_1">
</div>

Now I'd love to be able to do the same with radio buttons and checkboxes. The output should be something like:

<label><span></span><input ... ></label>
<label><span></span><input ... ></label>
<label><span></span><input ... ></label>

UPDATE 2

(almost a solution)

I have something that can somehow do what I want, i.e. having a span per input in a collection of radio buttons or checkboxes. It outputs the span after the input tag, but before the text so it kinda works.

The solution doens't make use of any initializer, it's just a lambda that runs for every object in the collection.

Assuming you have an array which called choices:

choices = [ 
  { label: "Foo", value: "foo" },
  { label: "Bar", value: "bar" }
]

View

# the view code
<%= ff.input :xxx, 
      collection: choices, 
      label_method: -> (choice){ "<span></span>#{ choice[:label] }".html_safe } %>

Output

<label><input ... ><span></span> Foo </label>
<label><input ... ><span></span> Bar </label>
Stalder answered 11/12, 2017 at 18:6 Comment(2)
Can you show us the code for the text one? and what you tried for the radio button (even if it didn't work)?Farver
I added the attempt with the string input. I added also what can be a solution. It's doesn't exactly do what I wanted but it's very close and can work for me.Stalder

© 2022 - 2024 — McMap. All rights reserved.