Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add HTML attributes to select options with Simple Form Rails?

I need to add a custom HTML attribute to each option for a select control. I'm using simple_form in Rails. Does anyone know how to do this? The attribute will be consumed by client-side JS.

For instance, I want to do something like this:

<%= f.input :group, collection: @groups, option_html: { data-type: lambda { |g| g[2] } } %> 

Which would produce (simplified):

<select>     <option value="1" data-type="primary">First Group</option>     <option value="2" data-type="secondary">Second Group</option>     <option value="3" data-type="secondary">Third Group</option> </select> 

Where @groups might look like this:

[     ['First Group', 1, 'primary'],     ['Second Group', 2, 'secondary'],     ['Third Group', 3, 'secondary'] ] 

Hoping to avoid having to make a custom control/wrapper. Thanks!

like image 767
YWCA Hello Avatar asked Jul 09 '13 17:07

YWCA Hello


2 Answers

You're close! easiest way is actually not using simple_form here. here's the simple_form documentation

<% options = @group.map { |g| [g.name, g.id, {'data-type' => g.group_type}] } %> <%= f.input :group, label: 'Group' do %>   <%= f.select :group, options, include_blank: 'Select a Group', class: 'form-control' %> <% end %> 

For your exact code it would be:

<% options = @group.map { |g| [g[0], g[1], {'data-type' => g[2]}] } %> <%= f.input :group, label: 'Group' do %>   <%= f.select :group, options, include_blank: 'Select a Group', class: 'form-control' %> <% end %> 
like image 90
Blair Anderson Avatar answered Sep 20 '22 21:09

Blair Anderson


simple-form only:

= f.input :group, @groups.map{|l| [l[0], l[1], {data: {type: l[2]}}]}

like image 39
Bruno Porto Avatar answered Sep 19 '22 21:09

Bruno Porto