In the last few days I wanted to create part of our address entry partial using text_field_with_auto_complete. I did some googling but in the end it required some brain power to figure out myself.
Adding them is easy. I have a Country, County and Location entry field so I added three text_field_with_auto_complete boxes, one for each like so:
<div class="formElement"><label>Country: </label>
<%= text_field_with_auto_complete
:country, :name,{}, :indicator => "country_activity" %>
<span id="country_activity" style="display:none;" ><%= image_tag 'spinner.gif'%>
</span></div>
and so on. The indicator attribute allows you to specify an element in the document which becomes visible while the text_field_withautocomplete is carrying out a query.
Then in the controller I added the methods required for the data query:
def auto_complete_for_country_name
auto_complete_responder_for_countries params[:country][:name]
end
private
def auto_complete_responder_for_countries(value)
@countries = Country.find(:all,
:conditions => ['Lower(name) LIKE ?', '%'+value.downcase+'%'],
:order => 'name ASC',
:limit => 10)
render :partial => 'auto_country_list'
end
Then in my partial:
<ul>
<% for country in @countries do -%>
<li><%=h country.name %>
<% end -%>
</ul>
That all works fine and it was easy to replicate the same thing three times, one for each field. Where I ran in to problems was when I tried to call the counties text box. I couldn't find out how to pass the country value in to county query, so as to only get the values for the selected country.
In typical rails fashion is turns out to be pretty easy, you use the with attribute of the text_box_with_auto_complete.
So your county text box becomes:
<div class="formElement"><label>County: </label><%= text_field_with_auto_complete
:county, :name, {},
:with => "'county[name]='+encodeURIComponent(element.value)+'&country_name='+$('country_name').value",
:indicator => "county_activity" %>
<span id="county_activity" style="display:none;" ><%= image_tag 'spinner.gif'%></div>
Then in your controller:
def auto_complete_for_county_name
auto_complete_responder_for_counties params[:county][:name] , params[:country_name]
end
private
def auto_complete_responder_for_counties(value, country)
@counties = County.find(:all,
:conditions => ['Lower(name) LIKE ? and country = ?', '%'+value.downcase+'%', country],
:order => 'name ASC',
:limit => 30)
render :partial => 'auto_county_list'
end
The code for the partial stays the same. Simple really
Comments
There are 0 comments on this post. Post yours →
Post a comment
Required fields in bold.