Edit DataTables source data, using form inside pop-up window

前端 未结 3 1977
长发绾君心
长发绾君心 2020-12-09 14:17

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 15:13

    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 into storage upon AJAX-request receipt).

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

    • append (by means of createdRow option) some anchor (row().index() or source object id property, etc) to your source data within some 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)
    })
    
    • append some anchor attribute (e.g. data-src) to your editor pop-up (I'll use bootstrap-4 modal for that purpose) nodes to link those input fields to corresponding source object properties:
    • upon clicking edit button, grab corresponding row data, populate editor pop-up 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');
    });
    
    • upon completing row data editing, store values into object:
    const modifiedData = {};
    $.each($('#editform input'), function(){
      Object.assign(modifiedData, {[$(this).attr('data-src')]:$(this).val()});
    });
    
    • 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();
        }
    });
    

    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.

    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  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+''}
        ],
      });
      //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();
          }
        });
      });
    });
    
    
    
      
      
      
    	
      
      
      
        
      
    
    
      
      

提交回复
热议问题