Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 + simple form + bootstrap Radio and checkbox as button w/ toggle function

I'm trying to get my radios and checkboxes to work as buttons w/ the toggle function as seen on twitters bootstrap page. link!

I've somehow managed to get those buttons to appear and function w/ the database, but when If the user returns to the page, they are not toggled. I was wondering if that's is possible or not. If yes, how can I implement that on my code? I'm using simple_form + twitter bootstrap.

Here is the code I'm using to display the radio button:

<div class="btn-group" data-toggle="buttons-radio">
<%= f.input :child_gender, :label => "Child gender?", :collection => [['Boy', 'Boy'], ['Girl', 'Girl'], :as => :radio_buttons, :input_html => { :data => {:toggle => 'buttons-radio'} }, :item_wrapper_class => 'btn btn-toggle btn-small inline' %>
</div>

And here is the code for checkbox button:

<div class="btn-group">
<%= f.input :child_size, :label => "What size?", :collection => child_size, :as => :check_boxes, :input_html => { :data => {:toggle => 'buttons-checkbox'} }, :item_wrapper_class => 'btn btn-toggle btn-small' %>
</div>

Here is the custom css I have for btn-toggle:

.btn-toggle input {
    display: none;
}

Any help is appreciated.

like image 499
Luiz Daluz Avatar asked Feb 18 '23 05:02

Luiz Daluz


1 Answers

Building from Nickl's answer and tweaking things to require no additional Javascript and to render the same semantic HTML that Bootstrap currently expects, here's my solution:

class ButtonRadioInput < SimpleForm::Inputs::CollectionRadioButtonsInput
  def input
    out = '<div class="btn-group" data-toggle="buttons">'
    label_method, value_method = detect_collection_methods
    collection.each do |item|
      value = item.send(value_method)
      label = item.send(label_method)
      active = ''
      active = ' active' unless
          out =~ / active/ ||
          input_html_options[:value] != value &&
          item != collection.last
      input_html_options[:value] = value unless active.empty?
      btn = 'btn'
      btn = "btn btn-#{item.third}" unless item.third.nil?
      out << <<-HTML
        <label class="#{btn} #{active}">    
          <input type="radio" value="#{value}" name="#{attribute_name}">#{label}</input>
        </label>
HTML
    end
    out << "</div>"
    out.html_safe
  end
end

And then to use this you would use SimpleForm as such:

=f.input :role, label: false, as: :button_radio, 
                    collection: [["Warm Up", :warm_up, :primary],
                                ["Small Sided", :small_sided, :primary],
                                ["Expanded", :expanded, :primary],
                                ["Game", :game, :primary]]

This will render code just like the radio-button examples from Bootstrap's own components page.

like image 57
Darren Hicks Avatar answered Feb 21 '23 09:02

Darren Hicks