3
votes

I have created a custom wrapper for simple_form but I can't seem to find a way to add data attributes to the generated wrapper element. I'm trying to add it to the inner wrapper class called switch.

I want to be able to add it to the wrapper, not in view layer if possible.

config.wrappers :toggle, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
  b.use :html5
  b.use :placeholder
  b.use :label
  b.wrapper :tag => 'div', :class => 'controls' do |ba|
    ba.wrapper :tag => 'div', :class => 'switch' do |box|
      box.use :input
    end
    ba.use :hint,  :wrap_with => { :tag => 'span', :class => 'help-block' }
    ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
  end
end

= form.input :element, :label => t('views.items.attributes.element'), :wrapper => :toggle

Output

<div class="control-group boolean optional">
  <label class="boolean optional control-label" for="item_element">Element</label>
  <div class="controls">
    <div class="switch">
      <input name="item[element]" type="hidden" value="0">
      <input class="boolean optional" id="item_element" name="item[element]" type="checkbox" value="1">
    </div>
  </div>
</div>

Desired Output

<div class="control-group boolean optional">
  <label class="boolean optional control-label" for="item_element">Element</label>
  <div class="controls">
    <div class="switch" data-label="blah" data-id="something">
      <input name="item[element]" type="hidden" value="0">
      <input class="boolean optional" id="item_element" name="item[element]" type="checkbox" value="1">
    </div>
  </div>
</div>
2

2 Answers

1
votes

@Learner's answer is close. The trick is to include an html hash:

ba.wrapper tag: 'div', 
           html: { data: { id: 'something', label: 'blah' }, 
           class: 'switch' do |box|
  box.use :input
end

Note: This approach works on the <builder>.wrapper methods, but not on config.wrappers, <builder>.use, etc.

0
votes

You can add :data => {:id=> 'something', :label => 'blah'} after the tag name in your wrapper

config.wrappers :toggle, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
  b.use :html5
  b.use :placeholder
  b.use :label
  b.wrapper :tag => 'div', :class => 'controls' do |ba|
    ba.wrapper :tag => 'div', :data => {:id=> 'something', :label => 'blah'}, :class => 'switch' do |box|
      box.use :input
    end
    ba.use :hint,  :wrap_with => { :tag => 'span', :class => 'help-block' }
    ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
  end
end

= form.input :element, :label => t('views.items.attributes.element'), :wrapper => :toggle

Even you could add name, and some values like the following:

:data => {:name => 'Stephen', :city_state => %w(Chicago IL)}