Dynamically add form elements

I’m trying to build a form where user can add more options if they want to.
The aim is to provide assisted SQL query form. So, after they enter 1 column and its condition, they can click + button and add more. Once the submit button is clicked, I want to combine every column and condition to form the SQL query. Something like this:

query = "Select " + selected_cols + " FROM TABLE WHERE " + col_1 + " " + condition_1 + and_or_or +  col_2 + " " + condition_2 ...

Here’s the structure of the form right now

def _assisted_query_form():
    options = table.schema.names
    options.append("*")
    k = 0

    subcol1, subcol2, subcol3, subcol4, subcol5 = st.columns([0.1, 0.3, 0.1, 0.3, 0.2])
    with subcol1:
        st.write("SELECT")
    with subcol2:
        st.multiselect("select", options=options, label_visibility="collapsed", index=len(options)-1, key="selected_columns")
    with subcol3:
        st.write("WHERE")
    with subcol4:
        st.selectbox("where", options=options, label_visibility="collapsed", key=f"where_{k}")
    with subcol5:
        st.text_input("condition", value="condition", label_visibility="collapsed", key=f"condition_{k}")

    add = st.selectbox("+", options=("AND", "OR", "None"), index=2)
    if add != "None":
        col, condition = st.columns(2)
        # input col and condition
    # repeat

I want to accomplish this using a loop or some structure like that that’s dynamic and allows user to input as many conditions as they want.
How can this be accomplished using streamlit?

Hi @AyushExel

There’s a related forum post showing a solution with code snippet on dynamically adding input widgets, which you can repurpose for your use case:

Hope this helps!

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