Jacquie Fan wrote:
Hi,all
I've used text_field_with_auto_complete for a while but still haven't figured out how to store the value that I selected from the suggested options. any hints?
Thanks!
There are a couple of ways to do it. The previous poster suggested one way which is to get it from the params like you would a normal text_field, however this only works if the value you select and display in the text_field part of the auto_completer is unique in the database.. e.g. if text_field_with_auto_complete :customer, :name then if name= params[:customer][:name] is not unique, ie Customer.find_all_by_name(name) returns more than one entry you need to be a little more tricky.
One method is mentioned here: http://www.dalemartenson.com/blog/?p=24 and I use this sometimes.
Another method I use is to put in the text_field a string like "23,Blogs,Fred", this is the id of the customer record, and the last,first name. Then I do this in the controller...
namecsv= params[:customer][:name] id,last,first= namecsv.split(',') customer= Customer.find(id)
I get the namecsv in the text box using this partial for the auto completer...
<ul class="auto_complete"> <% for customer in @customers do -%> <li class="big"> <div class="name"><%=h customer.fullname -%></div> <div class="code"><%=h "#{customer.id},#{customer.lname},#{customer.fname}" -%></div> <div class="email"> <span class="informal"><%=h "#{customer.email}" -%></span> </div> </li> <% end -%> </ul>
using this in the view...
text_field_with_auto_complete( :customer, :name, {}, {:select => 'code', :skip_style => true) %>
Notice the :select => 'code', this is critical as it tells it which part of the popup list to put into the text_field.
This is a little ugly and error prone so you need some error checking etc. The other method looks nicer on the screen but is more work in the background.
So use whichever method best suits your application.