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!
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 %>