brian-welch
brian-welch

Reputation: 461

How can I add classes to a simple_form input wrapper in Rails?

I need to add a data attribute to an f.association input in a simple form. To do this I found this article and subsequent reference to simpleform's documentation. It is easy enough to add classes with the standard syntax, I am wondering why it's proving difficult using a wrapper.

So rather than the standard:

<%= f.association :size, input_html:{class: 'sku-suffix-component'} %>

I am using:

<%= f.input :size, as: :select, input_html:{class: 'sku-suffix-component'} do %>
  <%= f.select :size, Size.all.map{ |s| [s.name, s.id, {'data-code-num' => s.code_num}] } %>
<% end %>

Much to my frustration, the added class is nowhere in the <select> tag (not to mention the missing other default classes and id naming convention [id="product_size_id" becomes id="product_size"]). I have tried various syntaxes and placements of the input_html hash.

Below you can see the difference in appearance etc. On the right is using the standard syntax. enter image description here

And here is the resulting html:

<select name="product[size]" id="product_size"> (...)

Compared with:

<select class="form-control select required sku-suffix-component" name="product[color_id]" id="product_color_id"> (...)

Upvotes: 0

Views: 1557

Answers (2)

Upendra Chahar
Upendra Chahar

Reputation: 116

Try this solution and if it is possible than create some link for jsfiddle so we can test and try to find solution

<%= f.input :size do %>
    <%= f.select :size, Size.all.map { |s| [s.name, s.id, { class: 'sku-suffix-component', 'data-code-num' => s.code_num }]}, input_html: { class: 'sku-suffix-component' }, include_blank: true %>
<% end %>

Upvotes: 1

brian-welch
brian-welch

Reputation: 461

I found the solution combining strategies that I found on separate posts.

The long and the short of it was to utilize the map method but not within a custom input wrapper.

<%= f.association :size, collection: Size.all.map{ |s| [s.name, s.id, {'data-code-num' => s.code_num}]}, input_html:{class: 'sku-suffix-component'} %>

This nets perfectly my desired <select> with an added class, and the <option>'s with a custom data- attribute.

<select class="form-control select required sku-suffix-component" name="product[size_id]" id="product_size_id">
  <option value=""></option>
  <option data-code-num="001" value="113">onesize</option>
(...)

Upvotes: 0

Related Questions