Parsing Values

After editing cells in the grid you have the opportunity to parse the value before inserting it into your data. This is
done using Value Parsers.

Value Parser

For example suppose you are editing a number using a text editor. The result will be a string, however you will
probably want to store the result as a number. Use a Value Parser to convert the string to a number.

columnDefs = [
    {
        # name is a string, so don't need to convert
        'field': 'name',
        'editable': True,
    },
    {
        # age is a number, so want to convert from string to number
        'field': 'age',
        'editable': True,
        'valueParser': {'function': 'Number(params.newValue)'}
    }
]

If using Cell Data Types, Value Parsers are set by default
to handle the conversion of each of the different data types.

The return value of a value parser should be the result of the parse, for example, return the value you want stored in
the data.

Below shows an example using value parsers. The following can be noted:

import dash_ag_grid as dag
from dash import Dash, html, callback, Input, Output
import json


app = Dash(__name__)

rowData = [
    {"item": f"Item-{i}","goodNumber": i * 4234, "badNumber": i * 9872}
    for i in range(1,9)
]

columnDefs = [
    {"field": "item"},
    {"field": "goodNumber", "headerName": "Good Number", 'valueParser': {'function': 'Number(params.newValue)'}},
    {"field": "badNumber", "headerName": "Bad Number"}
]

app.layout = html.Div(
    [
        dag.AgGrid(
            id="grid-value-parser",
            columnDefs=columnDefs,
            rowData=rowData,
            columnSize="sizeToFit",
            defaultColDef={"editable": True,  "cellDataType": False},
            dashGridOptions={"animateRows": False}
        ),
        html.Pre(id="output-value-parser")
    ]
)


@callback(
    Output("output-value-parser", "children"),
    Input("grid-value-parser", "cellValueChanged"),
    Input("grid-value-parser", "virtualRowData"),
)
def update(changed, data):
    return json.dumps(data, indent=2)

if __name__ == "__main__":
    app.run(debug=True)