Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a class to each select options with SimpleForm

I want to build a select input from an array (and not a collection of models), with SimpleForm, and have different classes for each options.

I would have hoped that this would work:

f.input :method, collection: [
    ["option text", "option_value_1", { class: "class_name_1" }],
    ["option text 2", "option_value_2", { class: "class_name_2" }]
]

The problem with that is it will generate:

<select>
    <option value="option text" class="class_name_1">option text</option>
    <option value="option text 2" class="class_name_2">option text 2</option>
</select>

How can I do what I want (value should be "option value") with simple form?

like image 635
Robin Avatar asked Feb 17 '23 08:02

Robin


2 Answers

This appears to be a limitation when using collections, see the author of SimpleForm's explanation here. He recommends a workaround of the form:

f.input :method, :as => :select do
  f.select :method, [['option text', 'option_value_1', {"class" => "class_name_1"}], ['option text 2', 'option_value_2', {"class" => "class_name_2"}]]
end
like image 127
Dan Wich Avatar answered Feb 20 '23 15:02

Dan Wich


You also can pass array of arrays as an argument

= f.input :status, collection: [['option text', 'option_value_1', {"class" => "class_name_1"}], ['option text 2', 'option_value_2', {"class" => "class_name_2"}]]
like image 43
ilgam Avatar answered Feb 20 '23 16:02

ilgam