PablocFonseca / streamlit-aggrid

Implementation of Ag-Grid component for Streamlit
https://pypi.org/project/streamlit-aggrid/
MIT License
992 stars 190 forks source link

GridResponse not updated on rowdrag #272

Open nathalieguillemain opened 1 month ago

nathalieguillemain commented 1 month ago

Hello

Thank you for the new version !

When using rowdrag the data is not beeing updated unless you explicitly select a row

Here an example with Row Edit and Row Drag in a form (same if not in a form)

Works if update_mode=MANUAL => when click on update button but this is not user Friendly

` df = pd.DataFrame(["apple","orange","banana",'tomato', "bean", "potatoe"],columns=["item"]) df["type"] = "" df_out = None df_rearranged=None with st.form("test") : st.session_state.dataframe = df type_dropdownlist = ('Fruit', 'Vegetable')

    gb = GridOptionsBuilder.from_dataframe(st.session_state.dataframe)
    gb.configure_default_column(editable=True, min_column_width=10)
    gb.configure_column('type', editable=True, cellEditor='agSelectCellEditor',
                        cellEditorParams={'values': type_dropdownlist}, singleClickEdit=True)

    gb.configure_column('item', editable=False, rowDrag=True,rowDragManaged=True, rowDragEntireRow=True)

    gb.configure_grid_options(**{
            "rowDragManaged": True,
            "rowDragEntireRow": True,
            "rowDragMultiRow": True,
            'animateRows': True,"rowDragMultiRow": True, "rowSelection": "multiple" })

    grid_options = gb.build()
    grid_height = 250
    grid_response = AgGrid(
        st.session_state.dataframe,
        gridOptions=grid_options,
        height=grid_height,
        width='100%',
        key="tb2",
        data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
        update_mode=GridUpdateMode.GRID_CHANGED
    )
    val = st.form_submit_button("Save")
    if val :
        df_out = grid_response['data']
        rows_id_after_sort_and_filter= grid_response['rows_id_after_sort_and_filter']
        df_rearranged = df_out.loc[rows_id_after_sort_and_filter].reset_index(drop=True)
        st.write(rows_id_after_sort_and_filter)

st.write(df_out)
st.write(df_rearranged)`
nathalieguillemain commented 1 month ago

In complement, in case of nested table, I cannot fin a way go get the nested re-ordering. I get the eddition but not the re-order.

Here a made a few changed on the nested table example

import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder, JsCode, GridUpdateMode, DataReturnMode
import pandas as pd
import numpy as np
import requests

url = "https://www.ag-grid.com/example-assets/master-detail-data.json"
r  = requests.get(url)
data = r.json()

df = pd.read_json(url)
df["callRecords"] = df["callRecords"].apply(lambda x: pd.json_normalize(x))

type_dropdownlist = ('Short', 'Long')

gridOptions = {
    # enable Master / Detail
    "masterDetail": True,
    "rowSelection": "multiple",

    # the first Column is configured to use agGroupCellRenderer
    "columnDefs": [
        {
            "field": "name",
            "cellRenderer": "agGroupCellRenderer",
            "checkboxSelection": True,
        },
        {"field": "account"},
        {"field": "calls"},
        {"field": "minutes", "valueFormatter": "x.toLocaleString() + 'm'"},
    ],
    "defaultColDef": {
        "flex": 1,
    },
    # provide Detail Cell Renderer Params
    "detailCellRendererParams": {
        # provide the Grid Options to use on the Detail Grid
        "detailGridOptions": {

            "rowDragManaged": True,
            "rowDragEntireRow": True,
            "rowDragMultiRow": True,
            'animateRows': True, "rowDragMultiRow": True,
            "columnDefs": [
                {"field": "callId", "editable":False, "rowDrag":True,"rowDragManaged":True, "rowDragEntireRow":True},
                {"field": "direction"},
                {"field": "number", "minWidth": 150},
                {"field": "duration", "valueFormatter": "x.toLocaleString() + 's'"},
                {"field": "switchCode", "minWidth": 150},
                {"field" : 'calltype', "editable":True, "cellEditor":'agSelectCellEditor',
                                    "cellEditorParams":{'values': type_dropdownlist}, "singleClickEdit":True}
        ],
            "defaultColDef": {
                "sortable": True,
                "flex": 1,
            },
        },
        # get the rows for each Detail Grid
        "getDetailRowData": JsCode(
            """function (params) {
                params.successCallback(params.data.callRecords);
    }"""
        ),

    },
    "rowData": data
}
tabs = st.tabs(["Grid", "Underlying Data", "Grid Options", "Grid Return"])
with tabs[0]:
    r = AgGrid(
        None,
        gridOptions=gridOptions,
        allow_unsafe_jscode=True,
        enable_enterprise_modules=True,
        update_mode=GridUpdateMode.GRID_CHANGED,
        data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
        key="an_unique_key",
    )

with tabs[1]:
    st.write(data)

with tabs[2]:
    st.write(gridOptions)

# tabs =  st.tabs(['Selected Rows','gridoptions','grid_response'])

# with tabs[0]:
st.write(r.get("selected_rows"))
st.json(r.get("selected_rows").to_json(orient="records", indent=2))