Dynelight
Dynelight

Reputation: 2162

Allowing some enabled and disabled option on collection_select

I am trying to populate a dropdown box on a view that has all the states. This works just fine:

<%= f.collection_select :state_id, @states, :id, :name %>

Now, I need to make the following: Some states are going to be disabled for choosing, but they still have to appear on the dropbown list.

How can I achieve this? (I can populate an additional list for these states).

Upvotes: 2

Views: 1281

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176562

collection_select internally relies on options_from_collection_for_select helper.

Rather than using the collection_select directly, you can use select and pass the result of a options_from_collection_for_select call. The reason you may want to call options_from_collection_for_select directly, is because this method also accepts an optional selected parameter that could be used to pass a value for the disabled items.

selected can also be a hash, specifying both :selected and/or :disabled values as required.

The value of the option can be one of the following

If selected is specified as a value or array of values, the element(s) returning a match on value_method will be selected option tag(s).

If selected is specified as a Proc, those members of the collection that return true for the anonymous function are the selected values.

Therefore, if you pass { disabled: [1, 3, 5] } the items 1, 3, 5 will be disabled. Of course, the value must match the value of the option. You can also pass a block.

To be honest, this Rails helper looks quite complicated to me. Another option is to still use select directly, but create your own helper to generate the string of HTML option items and pass the string directly to the select (which is what options_from_collection_for_select is doing, with a not extremely simple API).

Upvotes: 3

Related Questions