How to automatically change value of dependent select box inside st.form

I have a problem in st.form. I want to do a city search by province. If I don’t apply it to st.form I don’t have any problem. On the other hand, when I want to do a city search by province, the value in the city select box does not change automatically, because in the st.form I perform a city search query by province.
here’s the code:

with st.form(key=‘form_parameters’):
# Create a dictionary of provinces and cities
city_choice = {‘province’ : data[‘Province Name’],
‘city’ : data[‘City Name’].drop_duplicates()}
# Create dataframe from dictionary
list_city_province = pd.DataFrame(choice_city)
# Create a provincial data variable from the province column from the data above
data_province = list_city_province[‘province’].drop_duplicates()
# with st.form(key=‘form_parameters’):
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
col_name = st.text_input(‘Enter your name’)
# Create a selectbox for a selection of provinces
select_province = st.selectbox(‘Select Province’, data_province.sort_values(ascending=True))
# Create a dataframe for the selected province
if select_province == select_province:
df1 = province_city_list.loc[provincial_city_list.province==province_select]
# Create a container variable for the city name of the selected province
df2 = df1.city.dropna().drop_duplicates()
# Create a select box to select a city
select_city = st.selectbox(‘Select City’, df2.sort_values())
submitted = st.form_submit_button(‘Recommend Me!’)

1 Like

Hi @fahmihamzah84 , here’s a thumb rule: if your widgets have any dependency logic attached to them, do not use a form.

Cheers

1 Like

thanks for your answer, I’m stuck at this streamlit features.

when I create dependent selectbox out of st.form, it works!
but in st.form it doesn’t.
what a strange feature!

The whole purpose of st.form is to have widgets that don’t update their state until you submit the form. None of the internals of Streamlit are aware of what has been selected inside of a form until it’s submitted. If you have something for which you want a real-time response, that thing should not be inside of a form.

In the case of widget A sets the conditions for widget B (e.g. A is a list of state, and B is a list of cities within the selected state). You can put B inside of a form as the one receiving the change, but you should not put A inside a form as it is the one causing the change.

thanks for your answer!

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.