Saving changes in SlickGrid

筅森魡賤 提交于 2019-11-27 18:24:44
Jim OHalloran

The trick to saving the SlickGrid is to realise that the grid will update the array of data that you supplied when creating the grid as the cells are edited.

The way I then save that is to include a form with a submit button and a hidden field below the grid. I trap the submit event and use the JSON plugin to serialise the array and place it in the hidden field. On the server side you'll receive a JSON string which you can deserialise, loop through and write to the database.

Assuming your array of data is called "data" like the samples, the following should work for you:

<form action="?" method="POST">
  <input type="submit" value="Save">
  <input type="hidden" name="data" value="">
</form>
<script>
  $(function() {
    $("form").submit(
      function() {
        $("input[name='data']").val($.JSON.encode(data));
      }
    );
  });
</script>
lclark

For completeness, a minimal example demonstrating the usage of onCellChange, referred to in Jim OHalloran's post.

For more information, and to see all events that can be utilized similarly to onCellChange, see comments at the beginning of the SlickGrid source.

<head>
  <!-- boilerplate omitted ... -->
  <script type="text/javascript">
      var grid;

      var options = {
          enableCellNavigation: true,
          enableColumnReorder: false,
          autoEdit: false,
          editable: true,
      };

      var columns = [
          {id: "item_key", name: "Key",   field: "item_key" },
          {id: "value",    name: "value", field: "value",   editor: LongTextCellEditor }
      ];

      var data = [
          {item_key: "item1", value: "val1"},
          {item_key: "item2", value: "val2"},
      ];

      $(document).ready(function () {
          grid = new Slick.Grid($("#myGrid"), data, columns, options);

         //Earlier code for earlier version of slickgrid
         // grid.onCellChange = function (currentRow, currentCell, item) {
         //      alert(currentRow+":"+currentCell+"> key="+item['item_key']+", value="+item['value']);

          //Updated code as per comment.
          grid.onCellChange.subscribe(function (e,args) { 
                 console.log(args); 
             });

          };
      });
  </script>

</head>
<body>
  <div id="myGrid" style="height:10em;"> </div>
</body>
Jim OHalloran

While I'm personally using the JSON serialize and submit in a hidden field approach from my previous answer another approach could be to trap the onCellChange event fired by SlickGrid after a cell value has changed and make an Ajax call to the server to save the changed value. This will result in lots of small Ajax requests to the server (which may increase load) but updates the server as soon as changes are made.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!