I have a form with contingent select boxes (the state is contingent on
the country selected, so when the country selected changes, the state
changes – I am using the Carmen plugin for getting my state names and
country names together, but not the functionality I am interested in
achieving).
Everything works fine except I cannot figure out how to amend my code
such that:
A. When the form is first rendered the state select box is empty (even
if there is a country showing, and the user (what I am calling an
“Associate” in terms of the model) HAS a state selected in his model. -
and-
B.If I have, say, a state selected, I change the country, don’t select
a state for that country, then go back and select the original country
(for which I have a state selected) it still doesn’t display the
selected state – just the list of states, unselected, in the state
select box (I believe the solution to #1, above, should solve this
too).
Ive scoured the net for examples of related matters, but cannot find
one similar to this. I am certain the solution must be little more
than a few lines of code which I am entirely oblivious to. Can someone
help me here? -JannaB
Here is the code I am using:
First, I have a model called Associates (for simplicity in
demonstration here, the only two members of Associates are state and
country, both Strings), and the /views/associates/_form.html.erb, as
follows:
<% form_for @associate do |f| %>
<%= f.error_messages %>
<%= f.label :city %>
<%= f.text_field :city %>
<%= f.label :state %>
<%= render :partial => 'get_states' %>
<%= f.label :country %>
<%= f.country_select :country, Carmen.default_country, {},
{
:onChange => remote_function( :url => { :action =>
'_get_states' }, :update => "state", :with => "'country=' +value")
} %>
<%= f.submit "Submit" %>
<% end %>"
Note that I have a partial that gets called, /views/associates/
_get_states.html.erb:
<% if @states !=nil %>
<% for state in @states %>
Then, in my AssociatesController, I put in the method _get_states:
def get_states
#essentially, this requires the 2 letter code for the country
selected, so if ‘united_kingdom’ is selected
#it converts to UK and gets its “states”. It also handles the default,
which is already specified properly
q = params[:country]
if(q!=Carmen.default_country)
q1 = q.gsub!("", " ")
if(q1!=q && q1!=nil)
q = q1.titleize
else
q.capitalize!
end
q = Carmen::country_code(q)
end
@states = Carmen::states(q)
end