Thursday, July 15, 2010

Modifications in rails auto_complete plugin to pass id as param.

The auto_complete plugin explain in railscasts passes the selected name as param.
Rails Autocomplete
In most cases we want to pass the select value id instead of name.
To pass the id instead of name in the above link all we need to do is


<!-- categories/index.js.erb -->
<%= auto_complete_values @categories, :name, :id %>
<%= text_field_with_auto_complete :product, :category_name, { :size => 15 }, { :url => categories_path(:js), :method => :get, :param_name => 'search', :after_update_element => "function(text_field, li_element){$('product_category_id').value = $('text_' + li_element.id).value;}"}) %>
<%= hidden_field "product", "category_id" %>
 
<!-- application_helper -->
  def auto_complete_values(entries, text_field, value_field, phrase = nil)
    return unless entries
    items = entries.map do |entry|
      content_tag("li", phrase ? highlight(entry[text_field], phrase) : h(entry[text_field]), {:id => entry[value_field]}) +
      hidden_field_tag("text_#{entry[value_field]}", entry[value_field])
    end
    content_tag("ul", items.uniq, {:style=> "height: 150px; overflow:auto;"})
  end

Note: In case you want to trigger an event on select of autocomplete list then all you want to do is modify after_update_element
Ex: <%= text_field_with_auto_complete :company, :number, {:class => "title"}, {:url => autocomplete_company_numbers_path(:js), :method => :get, :param_name => 'search', :after_update_element => "function(text_field, li_element){window.location.href='/company__numbers/show/' + $('text_' + li_element.id).value;}"} %>

No comments:

Post a Comment