Aggrid - Unselect all Rows

Hello, I would like to add a button in my Streamlit project to clear all the rows selected in an Aggrid Table with checkbox. Is there a way of doing it ? I tried various things (i.e. api.deselectAll()) but could not make it). Thanks for your help.

1 Like

hi @Gegeh , you can add a checkbox to the column header during the grid configuration:

With this checkbox, you can de/select all rows.

Cheers

3 Likes

Thank you very much for your prompt answer. Highly appreciated.

1 Like

Hi Shawn, Iā€™m appreciate your last post, very useful. May I ask if it possible to get the headerchecbox already selected when Streamlit app is launched.
Bests!

Philippe

Hi @Philippe_Franco , there are probably 2 ways to do this, both of which I have not tried out.

  1. Pre-selection:
    a. Find out the number of dataframe rows that feed into your aggrid (using a command such as totrows = df.shape[0])
    b. Configure your aggrid initially with
    gb.configure_selection(ā€˜multipleā€™, pre_selected_rows=[1, totrows])

  2. I suppose you could also use the aggrid API, which I have not attempted at all (because I never had the need to)

Cheers

Shawn

Hi all,

Has anyone successfully used the aggrid APIā€™s deselectAll() function for the Streamlit-aggrid component? In case you can share an example :slight_smile: Thanks a lot.

Hello Shawn, Thank you for your help!

Hi @Shawn_Pereira ,
I am trying to set this for the first column in my table -

gb.configure_column("year", headerCheckboxSelection = True)

I am getting the following error -

TypeError: list indices must be integers or slices, not str

If I understand correctly, I am supposed to pass the column name. Would you have some idea about what is going wrong?

The table is functioning fine without this line and I am able to select individual rows.

This is the full code in case it helps -

gb = GridOptionsBuilder.from_dataframe(df_country_rank_nb_customers)
gb.configure_pagination(paginationAutoPageSize=True)  # Add pagination
gb.configure_side_bar()  # Add a sidebar
gb.configure_selection('multiple', use_checkbox=True) #Enable multi-row selection
gridOptions = gb.build()
gb.configure_column("year", headerCheckboxSelection = True)

grid_response = AgGrid(
    df_country_rank_nb_customers,
    gridOptions=gridOptions,
    data_return_mode="AS_INPUT",
    update_mode="GRID_CHANGED", #options -> GRID_CHANGED, SELECTION_CHANGED, MODEL_CHANGED
    fit_columns_on_grid_load=True,
    theme="blue",  # Add theme color to the table Available options: ['streamlit', 'light', 'dark', 'blue', 'fresh', 'material']
    enable_enterprise_modules=True,
    height=350,
    width="100%",
    reload_data=False,
)

data = grid_response["data"]
selected = grid_response["selected_rows"]
df1 = pd.DataFrame(selected)  # Pass the selected rows to a new dataframe df1

Thanks.

Hi @mjo , I donā€™t have my laptop with me, but you can try out these two things:

  1. Move the line:
    gb.configure_column(ā€œyearā€, headerCheckboxSelection = True)

above the line:
gridOptions = gb.build()

in your code and check. If that doesnā€™t work:

  1. Please check if field name (year) exactly matches your df field name.

Cheers

1 Like

Hi @Shawn_Pereira ,
Thanks for your quick reply. Option 1 suggested by you worked :slight_smile: Thanks!

Just solved this like so

import streamlit as st
import streamlit.components.v1 as components
from st_aggrid import AgGrid, GridUpdateMode, ColumnsAutoSizeMode, JsCode
from st_aggrid.grid_options_builder import GridOptionsBuilder

# Add event listener that can access the grid api when onFirstDataRendered lifecycle event is called
js = JsCode("""
 function(event) {
    const api = event.api; 
     window.addEventListener('clear.rows', (e) => {
         api.deselectAll(); 
     });    
 }
 """)

gd = GridOptionsBuilder.from_dataframe(YOUR_DATA_HERE)
gd.configure_grid_options(ColumnsAutoSizeMode=ColumnsAutoSizeMode.FIT_CONTENTS, onFirstDataRendered=js)
gd.configure_selection(selection_mode='multiple', use_checkbox=True)

gridoptions = gd.build()

grid_table = AgGrid(YOUR_DATA_HERE,
                    height=250,
                    gridOptions=gridoptions,
                    allow_unsafe_jscode=True,
                    update_mode=GridUpdateMode.SELECTION_CHANGED)

# Clear button
if st.button('clear'):
    clearJs = '''<script>
     ((e) => {
        const iframe = window.parent.document.querySelectorAll('[title="st_aggrid.agGrid"]')[0] || null;
        if(!iframe) return;
        iframe.contentWindow.dispatchEvent( new Event('clear.rows'));
     })()
    </script>
    '''
    components.html(clearJs)
2 Likes

Excellent ! It works perfectly. Thank you very much.

i need the same thing but it is not workingā€¦ need to unselect the select rows and also the form to disappear
elif funct == ā€˜Update Plant Detailsā€™:

    dfP = plant_data(plant_name_)

    if len(dfP) > 0:
        grid_table_P = 0
        # grid_table_P["selected_rows"] = None
        dfP = dfP.sort_values(by='Shop Name', ascending=True)
        dfP = dfP[['Shop Name', 'Plant Address', 'Electricity_tariff',
                'OEE', 'Availability', 'Performance', 'Quality']]

        gd = GridOptionsBuilder.from_dataframe(dfP)
        gd.configure_selection(selection_mode='single', use_checkbox=True)
        gd.configure_column("Shop Name", headerCheckboxSelection = True)
        grid_options = gd.build()
        grid_options['columnDefs'] = column_plant

        grid_table_P = AgGrid(dfP, gridOptions=grid_options, custom_css=custom_css,
                           enable_enterprise_modules=False, allow_unsafe_jscode=True, autoSizeColumns=False,reload_data=True,
                            update_mode=GridUpdateMode.SELECTION_CHANGED, theme="material", key='psu')
        
        selected_row_pu = grid_table_P["selected_rows"]

        dfn = pd.DataFrame(selected_row_pu)


        if selected_row_pu:
            

            p2 = dfn['Shop Name'][0]
            p3 = dfn['Plant Address'][0]
            p4 = dfn['Electricity_tariff'][0]
            p5 = dfn['OEE'][0]
            p6 = dfn['Availability'][0]
            p7 = dfn['Performance'][0]
            p8 = dfn['Quality'][0]

            val =("Update {}".format(p2))
            st.warning(val)

            button_label = "Edit the data"

            form = st.form(key='form1', clear_on_submit=True)

            p_plant_address = form.text_input("Enter the Plant Address", value=p3)
            p_plant_electricity_tariff = (form.text_input("Enter the Electricity Tariff(Value should be in numeric)", value=p4))
            p_oee = form.text_input("Enter the value for Oee threshold(Value should be in numeric)", value=p5)
            p_availability = form.text_input("Enter the value for availability thresholf(Value should be in numeric)", value=p6)
            p_performance = form.text_input("Enter the value for perfomance threshold(Value should be in numeric)", value=p7)
            p_quality = form.text_input("Enter the value for quality threshold(Value should be in numeric)", value=p8)


            button_press = form.form_submit_button(
                label=f"{button_label}")

            if button_press:
                
                if all(is_numeric(value) for value in [p_plant_electricity_tariff, p_oee, p_availability, p_performance, p_quality]):
               
                    edit_data_plant(p2, p_plant_address, p_plant_electricity_tariff, p_oee, p_availability, p_performance, p_quality, plant_name_)
                    form_visible = False
                    clearJs = '''<script>
                    ((e) => {
                        const iframe = window.parent.document.querySelectorAll('[title="st_aggrid.agGrid"]')[0] || null;
                        if(!iframe) return;
                        iframe.contentWindow.dispatchEvent( new Event('clear.rows'));
                    })()
                    </script>
                    '''
                    components.html(clearJs)
                    st.experimental_rerun()

                    
                    
                else:
                    st.warning("Warning: Non-numeric value entered. Please enter numeric values for the specified thresholds and Tariff")            
          

    else:
        st.warning("Data Not Available for Plant Details")