开发者

Saving data from slickgrid

开发者 https://www.devze.com 2023-02-07 01:04 出处:网络
Can anyone please tell me how to identify the rows which I added or edited/updated in slickgrid. I am trying to save data to DB using Jquery AJAX. and I am using dataview option.

Can anyone please tell me how to identify the rows which I added or edited/updated in slickgrid. I am trying to save data to DB using Jquery AJAX. and I am using dataview option. I need to save/update only those rows which are newly added/updated.

Than开发者_运维问答ks in advance.


The first thing you need to make sure is that each row was initialized with a unique id from the server side (e.g. the primary key value of the row from the database).

Then you can use the grid.onAddNewRow event as follows

var editedRows = {}
grid.onAddNewRow.subscribe(function(e, args) {
            var item = args.item;
            editedRows[item.id] = item;
        });

When the user clicks the save button, you simply post the editedRowsobject to the server. Your php script can then iterate over the submitted row ids and update all changed rows in the dvs.

Note: my code is untested, but you should check http://mleibman.github.com/SlickGrid/examples/example3-editing.html to get an understanding of editing in slickgrid.


you can eaily hook the onCellChange event to the grid.

grid.onCellChange = function (row, col, dataRow) {
   //  enter your code here
}

(row,col) is the current cell and dataRow contains the data in that row.


i can see it an old post , but i had the same issue ,so thought about sharing how i did finally

you will need to follow fbuchinger recommendations ,

create an array to hold all changes and then post that array back to the server as below

    //#region standard set of options and vars always there

    var grid;
    var data = [];
    var columns = [];
    var editedRows = []; //array to hold all changes 

    var options = {
        editable: true,
        enableAddRow: true,
        enableCellNavigation: true,
        asyncEditorLoading: false,
        autoEdit: true ,
        showFooterRow: true,
    };

    var checkboxSelector = new Slick.CheckboxSelectColumn({
        cssClass: "slick-cell-checkboxsel"
    });

    columns.push(checkboxSelector.getColumnDefinition()); // check box first
    // define columns
    columns.push(
        { id: "ID", name: "ID", field: "id", width: 120, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator, focusable: false },
        { id: "Name", name: "Name", field: "name", width: 120, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator, minWidth: 70, sortable: true, toolTip: "Full Name" },
        { id: "IsActive", name: "Is-Active", field: "IsActive", width: 120, cssClass: "cell-title", editor: Slick.Editors.Checkbox, formatter: Slick.Formatters.Checkmark, validator: requiredFieldValidator });

   //#endregion
    //#region using data part
    $(function () {
        // get data
        $.getJSON('/acActivity/getAcActivityList', function (Resultdata) {
            data = Resultdata;               
            grid = new Slick.Grid("#SlickGrid", data, columns, options);

            grid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: false }));

            // add plug ins
            grid.registerPlugin(new Slick.AutoTooltips({ enableForHeaderCells: true }));
            grid.registerPlugin(checkboxSelector);
            var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);


            grid.onAddNewRow.subscribe(function (e, args) {

                var item = args.item;
                //  create an id for new lines and items 
                var id = Math.random * 10000 * -1;
                item.id = id;
                editedRows.push(item);

                grid.invalidateRow(data.length);
                data.push(item);
                grid.updateRowCount();
                grid.render();
            });

            grid.onCellChange.subscribe(function (e, args) {

                // only add after last column in the row
                if (args.cell == args.grid.getColumns() - 1)
                    editedRows.push(args.item);


            });

        }).fail(function () {
            alert('Data retrieval Error');
        });

        //#region send data back t oserver
        $('#Savebtn').click(function () {
            console.log(editedRows);

            var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
            console.log(UpdatedRows);

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/acActivity/Edit",
                traditional: true,   //must be tru for arrray to be send 
                data: { 'arrayOfValues': UpdatedRows },
                dataType: "json",
                success: function (data) {
                    // here comes your response after calling the server
                    alert('Suceeded');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("error : " + jqXHR.responseText);
                }
            });
        });
        //#endregion

        //#region deleted all selected
        $('#DeleteSelectedbtn').on('click', function () {
            if (confirm("Are you sure to delete All Selected ?????")) {
                var selectedData = [];
                 var selectedIndexes;

                    selectedIndexes = grid.getSelectedRows();
                    jQuery.each(selectedIndexes, function (index, value) {
                        selectedData.push(grid.getDataItem(value).id);
                    });
                    console.log(selectedData);
                    var SelectedIds = selectedData.join(',') ;
                    console.log(SelectedIds);
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/acActivity/DeleteSelected",
                    data: JSON.stringify({ "ids": SelectedIds }),
                    dataType: "json",
                    success: function (data) {
                        grid.render();
                    },
                    error: function (err) {
                        alert("error : " + err);
                    }
                });
            }
        });
        //#endregion
    });

you will need to have 2 button on your page ,

  1. to save all changes as bulk save (both edit and add new )
  2. a deleted selected button to delete selected rows
0

精彩评论

暂无评论...
验证码 换一张
取 消