Ag-Grid component with input support

Use the CustomCSS feature to set the attributes of the classes of the header cell, then you can both change the background color and the centering of text.

custom_css = {
    ".ag-header-cell-label": {"justify-content": "center"},
    ".ag-header-group-cell-label": {"justify-content": "center"}
    }

grid_response = AgGrid(
 ...
    custom_css=custom_css,
)

@Shawn_Pereira : The column grouping example is exactly what I was looking for. However, I’m trying to add a checkbox (boolean) column in as a child column, but I can’t seem to get it to work using a custom cell renderer through JsCode. The gb[‘columnDefs’] workaround to get the column groups doesn’t seem to be accepting a custom cell renderer in the same way as gb.configure_column does (or any custom event handler, like onCellClicked, using jscode for that matter)

Any suggestions?

Hi @Bradley_Feldman, I think checkbox columns have already been implemented; refer Table (or grid) with multiple inputs - #2 by ferdy

Cheers

1 Like

@Shawn_Pereira: Yes, I’m trying to use Ferdy’s code. But how do you use it with gb[‘columnDefs’] within grouped parent/child columns, as opposed to using it with gb.configure_columns()? I can easily get it working with gb.configure_columns, but can’t get any Jscode event handlers to work with gb[‘columnDefs’].

Thoughts?

Hello, thanks for the great tool.

I’m getting this error when trying to run it, any ideas on how to solve it ?

On the subject of column and row grouping, does anyone know how to open Ag-Grid in Streamlit in Pivot mode and set the row, columns, and values? Is there a GridOptionsBuilder property for this?

Experimented some more and found that this can be set with:

gb = GridOptionsBuilder.from_dataframe(df)
gb.configure_grid_options(pivotMode= True)

And then use gb.configure column to set up the pivot fields.

1 Like

Hi, did you get a solution for this?
I solve it like this:
cellsytle_jscode = JsCode(“”"

        function(params) {
            if (params.data.B == 'yes' | params.data.B == 'cow' | params.data.B == 'can') {
                return {
                    'color': 'white',
                    'backgroundColor': 'red',
                    'border': 'outset',
                    'color': 'white',
                    'font-size': 'larger',
                    'font-weight': 'bold'
                }
            }
        };
    """)
1 Like

Hi @Bradley_Feldman, is this what you are looking for? Grouping + checkbox with aggrid?

image

Cheers?

@Shawn_Pereira: That’s awesome, but my request was much simpler! I was asking about being able to define “grouped” column headers and then be able to define a custom cell renderer (in this case, a checkbox column) within one of the child columns.

I’m displaying them now using the checkboxSelection:True column property, but that only works for a visual POC. I need to be able to add an event handler (such as Ferdy’s code) to them. It just seems like when defining grouped columns via gb[‘columnDefs’], I can’t add an injection of javascript through JsCode – my attempts are producing errors in the browser console.

Do you know of a method/workaround ?

can you please give an example on how you pre populated teh pivot table of your choice with row + column grouping as well as value aggfuncs of your choice?

Hi @Bradley_Feldman, I didn’t manage to find a solution to what you want to do - maybe, someone else might in future. However, you could see if this alternative works for you. The checkbox code is courtesy @ferdy (My aggrid version is 0.3.3)

import pandas as pd
import streamlit as st
from st_aggrid import JsCode, AgGrid, GridOptionsBuilder
from st_aggrid.shared import GridUpdateMode, AgGridTheme

checkbox_renderer = JsCode("""
class CheckboxRenderer{

    init(params) {
        this.params = params;

        this.eGui = document.createElement('input');
        this.eGui.type = 'checkbox';
        this.eGui.checked = params.value;

        this.checkedHandler = this.checkedHandler.bind(this);
        this.eGui.addEventListener('click', this.checkedHandler);
    }

    checkedHandler(e) {
        let checked = e.target.checked;
        let colId = this.params.column.colId;
        this.params.node.setDataValue(colId, checked);
    }

    getGui(params) {
        return this.eGui;
    }

    destroy(params) {
    this.eGui.removeEventListener('click', this.checkedHandler);
    }
}//end class
""")

df=pd.DataFrame({ "Name": ['Paul', 'Gina'], "Age": [43, 35], "Inducted": [True, False], 
                  "Firm": ['Google', 'Microsoft'], "JDesc": ['Analyst', 'Programmer']})
gridOptions = GridOptionsBuilder.from_dataframe(df)
gridOptions.configure_column('Inducted', editable=True, cellRenderer=checkbox_renderer)
gb = gridOptions.build()

mycntnr = st.container()
with mycntnr:
    htmlstr = f"<p style='background-color: #A7727D; color: #F9F5E7; font-size: 16px; border-radius: 7px; padding-left: 8px; text-align: center'>TI</style></p>"
    st.markdown(htmlstr, unsafe_allow_html=True)

    dta = AgGrid(df, gridOptions=gb, height=150, allow_unsafe_jscode=True, theme=AgGridTheme.ALPINE,
                update_mode=GridUpdateMode.SELECTION_CHANGED)

Cheers

@Shawn_Pereira : Thanks for providing this. I am already aware of doing it this way. As you acknowledge, you, like I, weren’t able to make it work for grouped columns.

The key source line is this:

gridOptions.configure_column(‘Inducted’, editable=True, cellRenderer=checkbox_renderer)
gb = gridOptions.build()

Whereas the “cellRenderer” can be declared and works with configure_columns, but does not work with the grouped column declaration shown below:

gb[‘columnDefs’] = [
{‘headerName’: ‘NJ’, ‘headerClass’: ‘blue-header’, ‘children’: [
{‘field’: ‘NJ_MP’, ‘headerName’: ‘MP Price’},
{‘field’: ‘NJ_OT’, ‘headerName’: ‘OT Price’},
{‘field’: ‘NJ_ST’, ‘headerName’: ‘Static Price’},
{‘field’: ‘NJ_DL’, ‘headerName’: ‘Delta’},
{‘field’: ‘NJ_SV’, ‘headerName’: ‘Below the Line Savings’},
{‘field’: ‘NJ_XY’, ‘headerName’: ‘Choose Savings’, ‘cellRenderer’: ‘checkbox_renderer’}

Perhaps @PablocFonseca can add a “configure_group_columns” feature that would allow use to do javascript injection (via Jscode) like it does with “configure_columns”?

I’m very interested in this. I have added checkboxes to a column (not the first column!) with the cellRenderer method above, but I would like a way of selecting all of these checkboxes at once:

+1

there you go team

ob.configure_column(‘execTime’, floatingFilter= True, filter = ‘agDateColumnFilter’)

image

2 Likes

looking to pin grouped row per:

effecteviely trying to set

    autoGroupColumnDef: {
        headerName: 'Consoles',//custom header name for group
        pinned: 'left',//force pinned left. Does not work in columnDef
        cellRendererParams: {
            suppressCount: true,//remove number in Group Column
        }

Is that even possible? thanks

Hi there,

I try to sort a basic numeric column named “Clicks” but it won’t work. As you can see in the screenshot, the column values are considered as strings:

I tried to cast the column to a numeric type as specified here:

options_builder.configure_column("Clicks", type=["numericColumn","numberColumnFilter"], valueFormatter="parseFloat(data.Clicks)")

But it doesn’t work either.

Thank you much in advance for your help,
Best

Hi @Louis_Monier, check if your dataframe column (dtype), which feeds into the aggrid, for Clicks is float (and not object /string).

Cheers

Hi,
i have some issues with column groups and datetime columns:

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

# without groups:
df = pd.DataFrame({"colA":["a", "b", "c"],
                   "colB":["a", "b", "c"],
                   "colC":["2022-01-01", "2022-02-01", "2022-03-01"]})
df["colC"] = pd.to_datetime(df["colC"])

gb = GridOptionsBuilder.from_dataframe(
    df
)
selection = AgGrid(
    df,
    enable_enterprise_modules=True,
    gridOptions=gb.build()
)

# with groups:
df2 = pd.DataFrame({"colA":["a", "b", "c"],
                   "colB":["a", "b", "c"],
                   "colC":["2022-01-01", "2022-02-01", "2022-03-01"]})
df2["colC"] = pd.to_datetime(df2["colC"])

gb = GridOptionsBuilder.from_dataframe(
    df2
)

gb.configure_column("group1",
    header_name="group1",
    children=[
        {
            "field": 'colA'
        },
        {
            "field": 'colB'
        },
        {
            "field": 'colC'
        },
    ]
    )
selection2 = AgGrid(
    df2,
    enable_enterprise_modules=True,
    gridOptions=gb.build(),
    key="grid2"
)

In the second Grid, with groups, columns are duplicated AND the datatype of the grouped columns is set to string, so that here, the datepicker-filter does not work.
If i change the df of the gridbuilder options to an empty dataframe, i have all groups set up properly, but the datecolumn is of type string.
I can adjust the configuration of the column as:

{
    "field": 'colC',
    "type":"customDateTimeFormat",
    "custom_format_string":'yyyy-MM-dd',
    "filter": 'agDateColumnFilter'
},

But the filter won’t work, as the column is not recognized as dates.

Has anyone seen similar behaviour? Am i missing something?

Best,
Max