tekin.co.uk

New in Rails 2.3: Disabled option tags and lambdas for selecting and disabling options from collections

As it seems to have slipped through the usual channels, I thought I’d document a couple of enhancements to the form option helpers here.

Disabled option tags

The form option helpers have been updated so that you can now specify disabled option tags:


<%= select(
  :post,
  :category,
  Post::CATEGORIES,
  :disabled => 'private'
) %>
<!— Give's you something like: —>
<select name="post[category]">
  <option>story</option>
  <option>joke</option>
  <option>poem</option>
  <option disabled="disabled">private</option>
</select>

Disabled option tags appear greyed out and cannot be selected by the user (or at least they do in normal browsers — see below).

Select tag with disabled option tags

Lambdas for selecting and disabling option tags from collections

You can now use anonymous functions to specify which members of a collection should be selected or disabled in the resultant option tags. For example, you may want to disable product sizes that are out of stock:


<%= options_from_collection_for_select(
  @product.sizes,
  :name,
  :id,
  :disabled => lambda { |size| size.out_of_stock? }
) %>

<!-- If small and medium returned true for the method out_of_stock?, you’d get something like: -->

<option value=“23“ disabled=“disabled“>small</option>
<option value=“24“ disabled=“disabled“>medium</option>
<option value=“25“>large</option>
<option value=“26“>extra large</option>

This works exactly the same for selecting values, simply pass your anonymous function in as :selected.

A word of caution — always coding defensively

Although disabled option tags are part of the HTML specification, Internet Explorer 6 and 7 do not support them and will display disabled option tags as selectable. And although there are hacks to get IE to behave, you can never guarantee that disabled values will not be submitted by someone constructing a html post. Therefor, it’s always best to code defensively and guard against the potential selection of disabled values in your controller actions.

Get more fab content like this straight to your inbox

You'll get an email whenever I have a fresh insight or tip to share. Zero spam, and you can unsubscribe whenever you like with a single click.

More articles on Ruby on Rails

Authored by Published by