How to create a `add filter` button which creates a new set of fields everytime it is clicked

Hello All,

I am new to streamlit. I want to create a form where user can provide multiple filters on the table columns and download data from table based on these filters. Here the table is static.

I want to create a add_filter button which creates a new set of fields everytime it is clicked.
fields set:
filer: selectbox, options=[β€˜col1’,β€˜col2’,β€˜col3’]
operator: selecbox, options= [β€˜=’,β€˜!=’,β€˜>’,β€˜>=’,β€˜<’,β€˜<=’]
value: textbox
connector: selectbox, options=[β€˜And’,β€˜Or’]

I wrote function to create dynamic field set but it is not working. Provided code below.

Code snippet:

## function for dynamic filter
def addFilterSet():
    col1 = st.session_state.col1
    col2 = st.session_state.col2
    col3 = st.session_state.col3
    col4 = st.session_state.col4
    counter = st.session_state.counter

    filter_val = col1.selectbox('Field', ['Select','Col1','Col2','Col3'], index=0, key='filter'+str(counter))
    operator_val = col2.selectbox('Operator', ['Select','>','>=','<','<=','=','!='], index=0, key='operator'+str(counter))
    value_val = col3.text_input('Value',placeholder='Enter', key='value'+str(counter))
    connector_val = col4.selectbox('Connector', ['Select','And','Or'], index=0, key='connector'+str(counter))
    st.session_state.counter += 1

## form creation
with st.container():
    st.header('Filter Section')

    col1, col2, col3, col4 = st.columns([2,1,2,1])
    if 'col1' not in st.session_state:
        st.session_state.col1 = col1
        st.session_state.col2 = col2
        st.session_state.col3 = col3
        st.session_state.col4 = col4
        st.session_state.counter = 0

    st.button(label='Add Filter', key='add_filter', on_click=addFilterSet())

Expected behavior:
Initially, only Add filter button should be present on the form
A new field set to be created everytime the Add filter button is clicked

Actual behavior:

Initially, one field set is appearing along with Add filter button. Once I clicked the button, getting error pop
Screenshot from 2023-05-27 19-05-43

Please let me know how to acheive the desired function.

Thank you,
Sownik Turaga.

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