使用弹出窗口内的表单编辑DataTables源数据 [英] Edit DataTables source data, using form inside pop-up window

查看:95
本文介绍了使用弹出窗口内的表单编辑DataTables源数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,该数据表使用ajax从数据库中获取记录.我想添加编辑工具提示,例如扩展为但免费.有没有插件可以做到这一点?如果没有,有人可以帮助我手动进行此操作吗?

I have a datatable that fetches records from database with ajax. I want to add the edit tooltip like jquery-datatables-editor extension to datatables but for free. Is there any plugin to do this? if not, can any one help me to do this manually?

这是我的JavaScript代码:

This is my JavaScript code:

$('#table_id').DataTable({
    "serverSide": true,
    "processing": true,
    "ajax": function (data, callback, settings) {
        $.ajax({
            url: '/some url',
            type: 'GET',
            data: data,
            success: function (data) {
                console.log(data)
            }
        });

    },
    "columns": [{
            "title": "edit",
            "data": null,
            "className": "center",
            "defaultContent": '<a href = "" class = "editor_edit"> Edit </a>  /  <a href = "" class = "editor_remove"> Delete </a>'
        }, {
            "title": "name",
            "data": "name"
        }, {
            "title": "id",
            "data": "id"
        },

    ]
});

推荐答案

由于您的问题(和已发布的代码示例)主要与可编辑行功能的前端部分有关,因此我将主要关注这一点,因为后端逻辑非常重要简单明了(在收到AJAX请求后更新/插入本地存储中的数据).

Since your question (and posted code sample) are mostly concerned with front-end part of editable rows feature I will focus on that primarily as backend logic is pretty much straightforward (update/insert data in local storage upon AJAX-request receipt).

为了实现以下逻辑,我建议:

In order to implement that feature following logic I may suggest:

  • 附加(通过 createdRow 选项)一些锚点( row().index() 或源对象id属性等)一些<tr>属性(例如rowindex),因此稍后您将知道要在哪个条目上修改服务器端:
  • append (by means of createdRow option) some anchor (row().index() or source object id property, etc) to your source data within some <tr> attribute (e.g. rowindex), so you will know later on which entry to modify server-side:
$('table').DataTable({
    ...
    createdRow: (tr, _, rowIndex) => $(tr).attr('rowindex', rowIndex)
})

  • 在编辑器弹出窗口中添加一些锚点属性(例如data-src)(我将使用模态)的<input>节点,将这些输入字段链接到相应的源对象属性:
    • append some anchor attribute (e.g. data-src) to your editor pop-up (I'll use bootstrap-4 modal for that purpose) <input> nodes to link those input fields to corresponding source object properties:
    • <div><label>PropertyX:</label><input data-src="propertyX"></input></div>
      

      • 单击 edit 按钮,获取相应的行数据,使用该数据填充编辑器弹出<input>字段,将锚点传递到已编辑的行(rowindex属性值)以弹出属性:
        • upon clicking edit button, grab corresponding row data, populate editor pop-up <input> fields with that data, pass anchor to edited row (rowindex attribute value) over to pop-up attribute:
        • //for table id 'example' handle clicking 
          //edit button having class 'edit'
          $('#example').on('click', '.edit', function () {
              //get clicked row invoking row() API method
              //against DataTables object assigned to dataTable
              const rowClicked = dataTable.row($(this).closest('tr'));
              //populate edit form with row data by corresponding
              //rowClicked property based on 'data-src' attribute
              $.each($('#editform input'), function () {
                  $(this).val(rowClicked.data()[$(this).attr('data-src')]);
              });
              //set modal attribute rowindex to corresponding row index
              $('#editform').attr('rowindex', rowClicked.index());
              //open up edit form modal
              $('#editform').modal('toggle');
          });
          

          • 完成行数据编辑后,将<input>值存储到对象中:
            • upon completing row data editing, store <input> values into object:
            • const modifiedData = {};
              $.each($('#editform input'), function(){
                Object.assign(modifiedData, {[$(this).attr('data-src')]:$(this).val()});
              });
              

              • POST数据(以及相应的rowindex)到服务器并重新加载( ajax.reload() )成功后的最新数据表:
                • POST data (along with corresponding rowindex) to the server and reload (ajax.reload()) up-to-date datatable upon success:
                • $.ajax({
                      url: '/editrow',
                      method: 'POST',
                      data: {id: $('#editform').attr('rowindex'), ...modifiedData},
                      success: () => {
                          $('#editform').modal('hide');
                          dataTable.ajax.reload();
                      }
                  });
                  

                  使用以下实时演示. > link ,并带有 delete 按钮的形式的奖励.

                  Complete live demo of that method you might examine in your browser's DevTools by the following link with some bonus in form of row delete button.

                  HTML和jQuery代码示例都可能如下所示(不可执行,因为没有支持的后端):

                  Both HTML and jQuery code sample might look as follows (not executable as there's no supporting backend):

                  $(document).ready(() => {
                  
                    //data table initialization
                    const dataTable = $('#example').DataTable({
                      ajax: {
                        url: '/getdata',
                        type: 'GET',
                        dataSrc: ''
                      },
                      dom: 't',
                      //use <tr> attribute 'rowindex' to anchor to source data row index
                      createdRow: (tr, _, rowIndex) => $(tr).attr('rowindex', rowIndex),
                      columns: [ 
                        {data: 'name', title: 'Name'},
                        //append 'Edit'/'Delete' buttons to the rightmost edge of the cell
                        {data: 'title', title: 'Title', render: (cellData, _, __, meta) => cellData+'<i class="delete fa fa-trash"></i><i class="edit fa fa-pencil"></i></button>'}
                      ],
                    });
                    //delete button handler
                    $('#example').on('click', '.delete', function() {
                      //extract the index of the row to delete
                      //from 'rowindex' attribute
                      const rowIndex = $(this)
                        .closest('tr')
                        .attr('rowindex');
                      //do AJAX-call to the backend
                      $.ajax({
                        url: '/deleterow',
                        method: 'DELETE',
                        data: {id: rowIndex},
                        //re-draw datatable with up to date data
                        success: () => dataTable.ajax.reload()
                      });
                    });
                    //edit button handler (open up edit form modal)
                    $('#example').on('click', '.edit', function(){
                      //get clicked row
                      const rowClicked = dataTable.row($(this).closest('tr'));
                      //populate edit form with row data by corresponding 
                      //rowClicked property based on 'data-src' attribute
                      $.each($('#editform input'), function(){
                        $(this).val(rowClicked.data()[$(this).attr('data-src')]);
                      });
                      //set modal attribute rowindex to corresponding row index
                      $('#editform').attr('rowindex', rowClicked.index());
                      //open up edit form modal
                      $('#editform').modal('toggle');
                    });
                    //submit edits handler
                    $('#editform').on('click', '#submitedits', function(){
                      //grab modified data into object
                      const modifiedData = {};
                      $.each($('#editform input'), function(){
                        Object.assign(modifiedData, {[$(this).attr('data-src')]:$(this).val()});
                      });
                      //send modified data to the backend
                      $.ajax({
                        url: '/editrow',
                        method: 'POST',
                        data: {id: $('#editform').attr('rowindex'), ...modifiedData},
                        success: () => {
                          //close the modal
                          $('#editform').modal('hide');
                          //re-draw datatable
                          dataTable.ajax.reload();
                        }
                      });
                    });
                  });

                  <!doctype html>
                  <html>
                  <head>
                    <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
                    <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
                    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
                  	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
                    <script src="https://use.fontawesome.com/937a319e2f.js"></script>
                    <script type="application/javascript" src="/main.js"></script>
                    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
                    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">  
                    <link rel="stylesheet" type="text/css" href="/main.css">
                  </head>
                  <body>
                    <!-- Table -->
                    <table id="example"></table>
                    <!-- Modal -->
                  		<div class="modal fade" id="editform" tabindex="-1" role="dialog">
                  			<div class="modal-dialog" role="document">
                  				<div class="modal-content">
                  					<div class="modal-header">
                  						<h5 class="modal-title">Row details</h5>
                  					</div>
                  					<div class="modal-body">
                  						<form>
                  						  <div class="form-group"><label>Name:</label><input data-src="name" class="form-control"></input></div>
                  						  <div class="form-group"><label>Title:</label><input data-src="title" class="form-control"></input></div>
                  						</form>
                  					</div>
                  					<div class="modal-footer">
                  						<button type="button" class="btn btn-outline-dark" data-dismiss="modal">Close</button>
                  						<button type="button" class="btn btn-outline-dark" id="submitedits">Save changes</button>
                  					</div>
                  				</div>
                  			</div>
                  		</div>
                  </body>
                  </html>

                  这篇关于使用弹出窗口内的表单编辑DataTables源数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆