How to use gridOptions.api in streamlit-aggrid

I want to get the selected rows to do some calculations.
Following is my code written with reference to this.

However the console raises an errot that Uncaught ReferenceError: gridOptions is not defined.

I am a novice in JavaScript. I tried to research with Google for a long time, and found several similar cases, but there not one has been solved.

Is there someone could help me?
Thanks a lot.

from st_aggrid import AgGrid, GridOptionsBuilder, JsCode
import pandas as pd
import streamlit as st

getContextMenuItems = JsCode("""
function getContextMenuItems(params) {
  var result = [
    {
      name: Show Selected Rows,
      action: () => {
        var selectedNodes = gridOptions.api.getSelectedRows();
	var selectedData = selectedNodes.map(node => node.data);
	console.log(`Selected Nodes:\n${JSON.stringify(selectedData)}`);
      },
      cssClasses: ['redFont', 'bold']
    },
    'separator',
    'copy',
  ];
  return result;
}
""")

grid_op = {
"enableRangeSelection": True,
"getContextMenuItems": getContextMenuItems,
}

df = pd.read_csv("somedata.csv")
options_builder = GridOptionsBuilder.from_dataframe(df)
options_builder.configure_grid_options(**grid_op)
grid_options = options_builder.build()
grid_table = AgGrid(df, grid_options, enable_enterprise_modules=True, editable=True, allow_unsafe_jscode=True)

Hi @CharlieLL, you don’t need the grid API to get the selected rows. You can get the selected rows by simply doing something like this:

MySelectedRows = Your AGgridVariableName[‘selected_rows’]

You can then output the value of MySelectedRows to the screen to verify.

Cheers

Hi. I know this feature. But it is not what I want.

I finally found the way that how to use gridOptions.api.

I learned it from here.
In the function onFirstDataRendered, the gridOptions was passed into the function as the parameter params.

So I just need to change gridOptions to params in my code.

getContextMenuItems = JsCode("""
function getContextMenuItems(params) {
  var result = [
    {
      name: Show Selected Rows,
      action: () => {
        var selectedNodes = params.api.getSelectedRows();
        var selectedData = selectedNodes.map(node => node.data);
        console.log(`Selected Nodes:\n${JSON.stringify(selectedData)}`);
      },
      cssClasses: ['redFont', 'bold']
    },
    'separator',
    'copy',
  ];
  return result;
}
""")

I also happen to this issue, I need to call api.sizeColumnsToFit(params), but don’t know how to do that.

Hello, please list some of your use cases. May I can help you on it.
你好,请列举一些你的使用案例。或者我可以帮你看看如何解决。

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