Search code examples
rubyformtastic

Display extra attributes for option tag in a Formtastic select


<% semantic_form_for(@buss, {:url => url, :html => {....}}) do |f| %>
....
<%= f.input :country, :label => 'Country:', :include_blank => true %>
....

and country select is rendered as..

 <li class="select required" id="business_country_input">
    <label for="business_country_id">Country:</label>
    <select id="business_country_id" name="business[country_id]">
      <option value=""></option>
      <option value="221">Åland Islands</option>
      <option value="32">Algeria</option>
      <option value="9">American Samoa</option>
     </select>
  </li>

So, how do i add extra parameters for option tag, say for example i need something like

 .....
  <option value="221" country-code="AA">Aland Islands</option>  
  <option value="32"  country-code="BB">Algeria</option>  
  <option value="9"  country-code="CC">American Samoa</option>  
 .....

Basically something like

<select id="country">
  <% @countries.each do |c| %>
     <option value="<%= c.id %>" country-code="<%= c.code %>"><%= c.name %></option>
  <% end %>
</select>

How it can be done with formtastic ?.


Solution

  • First define a helper for building your custom country options:

    def custom_country_options
      countries = ActionView::Helpers::FormOptionsHelper::COUNTRIES.map do |c|
        [c.downcase, c, {:country-code => c[0..1]}]
        #=> ["algeria", "Algeria", "Al"] 
      end
    
      return options_for_select(countries)
    end
    

    then in your form, you should be able to do:

    <%= f.input :country, :as => :select, :collection => custom_country_options %>
    

    Note: there's a chance that f.input :country will always create the default country dropdown, you may have to do f.input :custom_country or similar.