从 slickgrid 保存数据

发布于 2024-10-14 21:21:54 字数 135 浏览 5 评论 0原文

谁能告诉我如何识别我在 slickgrid 中添加或编辑/更新的行。我正在尝试使用 Jquery AJAX 将数据保存到数据库。我正在使用数据视图选项。 我只需要保存/更新那些新添加/更新的行。

提前致谢。

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.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

舞袖。长 2024-10-21 21:21:55

您需要确保的第一件事是每一行都使用服务器端的唯一 ID 进行初始化(例如数据库中该行的主键值)。

然后您可以使用 grid.onAddNewRow 事件,如下所示

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

当用户单击保存按钮时,您只需将 editedRows 对象发布到服务器即可。然后,您的 php 脚本可以迭代提交的行 ID 并更新 dvs 中所有已更改的行。

注意:我的代码未经测试,但您应该检查 http://mleibman.github。 com/SlickGrid/examples/example3-editing.html 了解如何在 slickgrid 中进行编辑。

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.

司马昭之心 2024-10-21 21:21:55

您可以轻松地将 onCellChange 事件挂接到网格。

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

(row,col) 是当前单元格,dataRow 包含该行中的数据。

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.

等往事风中吹 2024-10-21 21:21:55

我可以看到它是一个旧帖子,但我有同样的问题,所以考虑分享我是如何做的,最后

你需要遵循fbuchinger的建议,

创建一个数组来保存所有更改,然后将该数组发布回服务器,如下

    //#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
    });

所示您的页面上需要有 2 个按钮,

  1. 用于将所有更改保存为批量保存(编辑和添加新内容)
  2. 一个删除选定按钮,用于删除选定行

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文