Is it possible to have dynamic changing of inputs within a form? The blog post on forms says
“Also by definition, interdependent widgets within a form are unlikely to be particularly useful. If you pass the output of widget1
into the input for widget2
inside a form, then widget2
will only update to widget1
's value when the form is submitted.”
Consider the following app example that has a toggle button for the checkboxes and updates days based on month. I implemented the usage I want using st.session_state. My understanding is that this functionality in forms is not yet possible. Is that true? Would definitely make for cleaner code if it is possible. Thank you!
import streamlit as st
## Form Submission
st.header('Form Based Submission')
with st.form(key = 'Form Based Submission'):
birth_month = st.selectbox('Your Birth Month',['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
last_day = 31 if birth_month in ['Jan','Mar','May','Jul','Aug','Oct','Dec'] else 30
last_day = 29 if birth_month == 'Feb' else last_day
birth_day = st.selectbox('Your Birth Day', reversed(range(1,last_day+1)))
toggle = st.checkbox('Toggle All')
vanilla = st.checkbox('Do you like vanilla iceacream?', value = toggle)
chocolate = st.checkbox('Do you like chocolate icecream?', value = toggle)
mint = st.checkbox('Do you like mint icecream?', value = toggle)
output = {'Month':birth_month,'Day':birth_day,'Vanilla':vanilla,'Chocolate':chocolate,'Mint':mint}
submit = st.form_submit_button(label = 'Submit')
if submit:
st.write('You Form Submitted!')
st.write(output)
## Session State Based Submission
if 'output' not in st.session_state:
st.session_state['output'] = {}
if 'submitted' not in st.session_state:
st.session_state['submitted'] = False
st.header('Session State Based Submission')
birth_month = st.selectbox('Your Birth Month',['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],key='0')
last_day = 31 if birth_month in ['Jan','Mar','May','Jul','Aug','Oct','Dec'] else 30
last_day = 29 if birth_month == 'Feb' else last_day
birth_day = st.selectbox('Your Birth Day', reversed(range(1,last_day+1)),key='1')
toggle = st.checkbox('Toggle All',key = '5')
vanilla = st.checkbox('Do you like vanilla iceacream?', value = toggle, key='2')
chocolate = st.checkbox('Do you like chocolate icecream?', value = toggle, key='3')
mint = st.checkbox('Do you like mint icecream?', value = toggle, key =' 4')
submit = st.button('Submit', key = '6')
if submit:
st.session_state['submitted'] = True
st.session_state['output'] = {'Month':birth_month,'Day':birth_day,'Vanilla':vanilla,'Chocolate':chocolate,'Mint':mint}
if st.session_state['submitted']:
st.write('You Session State Submitted!')
st.write(st.session_state['output'])