Form button not working


I want to have a button that opens a form to take user input when clicked. The user writes stuff and clicks the submit button at which point the data is printed back to the app. I copied the st.form code on docs and modified it but when clicking the submit button, instead of displaying, the form closes and nothing happens.

Steps to reproduce

Code snippet:

add_case = st.button('Add new Case')

#on button click, display form
if add_case:
    with st.form("my_form"):
        #company name
        company_name = st.text_input("Company/Security name")
        #company sector
        company_sector = st.text_input("Company sector", value="None")
        hypothesis = st.text_area("Hypothesis")

        # Every form must have a submit button.
        submitted = st.form_submit_button("Submit")
        if submitted:
            st.write("slider", company_name, "checkbox", company_sector, "hypothesis", hypothesis)

Buttons won’t remember they were clicked with the next user action. If you need to nest buttons, then you’ll need to use session state. You can set buttons to record information into session state with a callback function, then set your conditionals to check that information in session state.

I pasted some sample code in a similar thread linked below. (The conditionals in this snippet could easily be nested or not as written; whatever your case requires.)

if 'stage' not in st.session_state:
    st.session_state.stage = 0

def set_stage(stage):
    st.session_state.stage = stage

# Some code
st.button('First Button', on_click=set_stage, args=(1,))

if st.session_state.stage > 0:
    # Some code
    st.button('Second Button', on_click=set_stage, args=(2,))
if st.session_state.stage > 1:
    # More code, etc
    st.button('Third Button', on_click=set_stage, args=(3,))
if st.session_state.stage > 2:
    st.write('The end')
st.button('Reset', on_click=set_stage, args=(0,))