2
votes

I'am making a new project with ag-grid. I've worked out an example where I can load data from a database into the grid. this works ! Now what I want to add is when a user changes a cell value the grid needs to send that changed value to the server and update the grid.

is there anyway how I can do this I can't seem to find any good examples for this.

this is my index.js

import {Grid} from 'ag-grid-community';
import 'ag-grid-enterprise';

import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";

const gridOptions = {

    rowModelType: 'serverSide',

    columnDefs: [
        {field: 'athlete'},
        {field: 'country', rowGroup: true, hide: true, editable: true},
        {field: 'sport', rowGroup: true, hide: true},
        {field: 'year', filter: 'number', filterParams: {newRowsAction: 'keep'}},
        {field: 'gold', aggFunc: 'sum', editable: true},
        {field: 'silver', aggFunc: 'sum'},
        {field: 'bronze', aggFunc: 'sum'},
    ],

    defaultColDef: {
        sortable: true,
        editable: true
    }

    // debug: true,
    // cacheBlockSize: 20,
    // maxBlocksInCache: 3,
    // purgeClosedRowNodes: true,
    // maxConcurrentDatasourceRequests: 2,
    // blockLoadDebounceMillis: 1000
};

const gridDiv = document.querySelector('#myGrid');
new Grid(gridDiv, gridOptions);

const datasource = {
    getRows(params) {
         console.log('test',JSON.stringify(params.request, null, 1));

         fetch('./olympicWinners/', {
             method: 'post',
             body: JSON.stringify(params.request),
             headers: {"Content-Type": "application/json; charset=utf-8"}
         })
         .then(httpResponse => httpResponse.json())
         .then(response => {
             params.successCallback(response.rows, response.lastRow);
         })
         .catch(error => {
             console.error(error);
             params.failCallback();
         })
    }
};

gridOptions.api.setServerSideDatasource(datasource);

server.js

  import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config.js';
import express from 'express';
import bodyParser from 'body-parser';

import OlympicWinnersService from './olympicWinnersService';

const app = express();
app.use(webpackMiddleware(webpack(webpackConfig)));

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.post('/olympicWinners', function (req, res) {
    OlympicWinnersService.getData(req.body, (rows, lastRow) => {
        res.json({rows: rows, lastRow: lastRow});
    });
});

app.listen(4000, () => {
    console.log('Started on localhost:4000');
});

kind regards

1

1 Answers

1
votes

You can tell the server about changes on onCellEditingStopped event:

const gridOptions = {
  ... ,
  onCellEditingStopped: function (event) {
    console.log("ask the server to update changed data in back end", event);
    let data = {rowIndex: event.rowIndex, id: event.data.id, col: event.column.colId, value: event.value}
    fetch(...).then(res => res.json()).then(res => {
      console.log("server is updated, now we can refetch the data if we want.");
      // gridOptions.api.purgeServerSideCache();
    });
  }
}

Normally ag grid updates the cached data on client, and you should only update it on server. But sometimes you need to get the fresh data from the server, You can do it with gridOptions.api.purgeServerSideCache();. it clears the cache and ask the server for new datas.

Live Demo