simple_form collection wrapper (radios buttons) : double encapsulation of items

后端 未结 3 970
醉话见心
醉话见心 2021-02-15 12:57

I\'d like to reproduce this html sequence of radio buttons with simple_form in order to make simple_form work with http://semantic-ui.com/ syntax :

  
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-15 13:30

    Summary:

    I had done something similar to this before by creating a custom input that inherits from SimpleForm::Inputs::CollectionRadioButtonsInput and overloading just a few methods. For more on custom input components, see https://github.com/plataformatec/simple_form/wiki/Adding-custom-input-components.

    In any case, the code below produces your desired html markup almost exactly using simple_form v2.1.0 and rails v3.2.15.

    Code:

    # File: app/inputs/semantic_ui_radio_buttons_input.rb
    
    class SemanticUiRadioButtonsInput < SimpleForm::Inputs::CollectionRadioButtonsInput
    
      # Creates a radio button set for use with Semantic UI
    
      def input
        label_method, value_method = detect_collection_methods
        iopts = { 
          :checked => 1,
          :item_wrapper_tag => 'div',
          :item_wrapper_class => 'field',
          :collection_wrapper_tag => 'div',
          :collection_wrapper_class => 'grouped inline fields'
         }
        return @builder.send(
          "collection_radio_buttons",
          attribute_name,
          collection,
          value_method,
          label_method,
          iopts,
          input_html_options,
          &collection_block_for_nested_boolean_style
        )
      end # method
    
      protected
    
      def build_nested_boolean_style_item_tag(collection_builder)
        tag = String.new
        tag << '
    '.html_safe tag << collection_builder.radio_button + collection_builder.label tag << '
    '.html_safe return tag.html_safe end # method end # class

    Then, in your form, just do:

    -# File: app/views//_form.html.haml
    
    -# Define the collection
    - child_care_coll = %w( Infant Toddler Preschool Kindergarten ).map!.with_index(1).to_a
    
    -# Render the radio inputs
    = f.input :child_care_type,
      :collection    => child_care_coll,
      :label_method  => :first,
      :value_method  => :last,
      :as            => :semantic_ui_radio_buttons
    

    Results:

    ...

    enter image description here

提交回复
热议问题