Ag-grid valueFormatter and grid width

Hi!

I’m currently working with Dash Ag-Grid and I’ve set up a valueFormatter as follows:

base_colDef = {
    "type": "rightAligned",
    "valueFormatter": {"function": "Number(params.value).toFixed(1) + ' %'"}
}

This setup formats every cell in the column, even if its value is blank or null, converting those cells to “0.0%”. I’d like to conditionally format the cells, such that only cells with actual numbers get the percentage formatting, while blank or null cells remain unformatted.

Has anyone encountered this and found a solution? Any guidance would be appreciated!

Also, on a separate matter, is there a way to auto update the grid width? If I change the browser size the grid shrinks altogether, when I expand the window back the grid would expand but the columns would stay shrank. Same happens here: Dash - you need two clicks on default size to change back to original size after changing size.

David

Hello @davzup89,

To make it so that the grid doesn’t do things with blanks, you can use:

params.value ? Formatfunction : null

As far as having the columns change size, I recommend using flex in the column defs, this will auto size based upon the grid total size.

It’s also good to pair this with a minWidth, otherwise you won’t be able to see the columns on very small screens.

2 Likes

Thanks. I tried this implementation

    "valueFormatter": {
        "function": """
        return params.value ? Number(params.value).toFixed(1) + ' %' : null;
        """
    }

but it would just leave everything unformatted in this case, even cells with values. Have I overlooked something?

Should be something like this:

"valueFormatter": {
        "function": """
        params.value ? Number(params.value).toFixed(1) + ' %' : null;
        """
    }

If that doesn’t work, then you probably need to make sure the params.value equal whatever you are running into.

You can always use the log function we built to see what the params are.

Great, it works. Interesting still that now it won’t format nulls as well as number 0.

Yeah, you have to do this:

"valueFormatter": {
        "function": """
        (params.value || params.value == 0) ? Number(params.value).toFixed(1) + ' %' : null;
        """
    }

0 defaults to bit behavior, where 0 is false and 1 is true.

1 Like

Thank you for your help!

1 Like

I am trying to implement a similar thing like this. But it does not work.

locale_de = """d3.formatLocale({
              "decimal": ",",
              "thousands": "\u00a0",
              "grouping": [3],
              "currency": ["", "\u00a0€"],
              "percent": "\u202f%",
              "nan": ""
            })"""
"valueFormatter": {
                                   "function": """
                                       (params.value || params.value == 0) ? f"{locale_de}.format(".2f")(params.value) : null;
                                       """
                               }

if I use it as follows it formats all cells including the empty ones:

"valueFormatter": {"function": f"{locale_de}.format('.2%')(params.value)"},

Thanks in advance for your help

Is just might be a typo, but try putting single quotes around the '.2f'

You should be doing it like this:

"valueFormatter": {
                                   "function": f"""
                                       (params.value || params.value == 0) ? {locale_de}.format(".2f")(params.value) : null;
                                       """
                               }

The way you had it, once in js would have read like this:

 (params.value || params.value == 0) ? f"{locale_de}.format(".2f")(params.value)

Which would result in a syntax error. You can always check the browser console to see errors. :slight_smile:

Thank you very much. It works!

1 Like

Hello everybody,

i am facing two issues that i suspect it has something to do with Grid formatting.

  1. When i delete the content of a cell in some columns the value 0,0… (zero) is asserted do this cell. This does not happen in every column. In the most of the columns i get an empty cell
  1. I have used ‘locale’ to change the decimal notation (point to comma). When i insert a decimal value to the cells in certain columns (same columns mentioned in first issue) i have to use point instead of comma notation. This does not happen in every column. In the most of the columns of the grid comma notation can be used.

dash==2.17.0
dash-ag-grid==31.2.0

The issues occur only in the columns: ‘col_F’, ‘col_G’, ‘col_H’, ‘col_I’. In all the remaining columns there are no issues. The part of the code is attached below.

column_def = []
        for col in parameter_ef_esp.columns:
            if col == 'col_A':
                column_def.append({'headerName': col,  # Name of table displayed in app
                                   'field': col,  # ID of table (needs to be the same as Excel sheet column name)
                                   "rowDrag": True,  # only need to activate on the first row for all to be draggable
                                   "checkboxSelection": True,  # only need to activate on the first row
                                   "cellStyle": {'textAlign': 'center'}})
            elif col in ['col_B', ]:
                column_def.append({'headerName': col,  # Name of table displayed in app
                                   'field': col,  # ID of table (needs to be the same as Excel sheet column name)
                                   "cellStyle": {'textAlign': 'center'}})

            else:

                if col == 'col_G':
                    cell_format = '\'.6f\''
                elif col == 'col_I':
                    cell_format = '\'.3f\''
                else:
                    cell_format = '\'.2f\''

                column_def.append({'headerName': col,  # Name of table displayed in app
                                   'field': col,  # ID of table (needs to be the same as Excel sheet column name)
                                   "cellStyle": {'textAlign': 'center'},

                                   "valueFormatter": {
                                       "function": f"""
                                           (params.value || params.value == 0) ? {self.locale_de}.format({cell_format})
                                           (params.value):null;
                                           """
                                   },
                                   # "valueFormatter": {"function": f"{locale_de}.format('.2f')(params.value)"},
                                   # 'cellEditor': 'agNumberCellEditor',
                                   })

        default_col_def = {
            # "filter": True,
            "filter": "agNumberColumnFilter",
            "resizable": True,
            "sortable": True,
            "editable": True,
            "floatingFilter": True,
            "minWidth": 200,
            "wrapHeaderText": True,
            "autoHeaderHeight": True,
            # "cellStyle": {'wordBreak': 'normal', 'whiteSpace': 'pre'},
        }

        grid = dag.AgGrid(
            id="snd_grid",
            className="ag-theme-alpine-dark",
            columnDefs=column_def,
            # rowData=df.to_dict("records"),
            rowData=parameter_ef_esp.to_dict(orient='records'),
            # rowData=data,
            columnSize="sizeToFit",
            defaultColDef=default_col_def,

            dashGridOptions={"undoRedoCellEditing": True, "undoRedoCellEditingLimit": 20, 'rowSelection': "multiple",
                             # 'rowDragManaged': True,
                             'domLayout': 'autoHeight',
                             "pagination": True, "animateRows": True,
                             "paginationPageSize": 20},
            style={"height": "100%", "width": "100%"},

        )