Редактировать исходные данные DataTables, используя форму во всплывающем окне - PullRequest
3 голосов
/ 30 июня 2019

У меня есть таблица данных, которая выбирает записи из базы данных с помощью ajax. Я хочу добавить всплывающую подсказку для редактирования, например расширение , но бесплатно. Есть ли плагин для этого? если нет, может ли кто-нибудь помочь мне сделать это вручную?

Это мой код JavaScript:

$('#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"
        },

    ]
});

Ответы [ 3 ]

4 голосов
/ 03 июля 2019

Поскольку ваш вопрос (и пример размещенного кода) в основном касаются входной части функции редактирования строк, я остановлюсь на ней в первую очередь, поскольку логика бэкэнда довольно проста (обновление / вставка данных в локальное хранилище при получении запроса AJAX-запроса)).

Чтобы реализовать эту функцию, следуя логике, я могу предложить:

  • добавить (с помощью опции createdRow) некоторую привязку (* 1009)*row().index() или свойство исходного объекта id и т. Д.) К исходным данным в рамках некоторого атрибута <tr> (например, rowindex), так что вы позже узнаете, какую запись следует изменить на стороне сервера:
$('table').DataTable({
    ...
    createdRow: (tr, _, rowIndex) => $(tr).attr('rowindex', rowIndex)
})
  • добавить некоторый атрибут привязки (например, data-src) к вашему всплывающему окну редактора (для этой цели я буду использовать модальный) <input> узлы для привязки этих полей ввода к соответствующим свойствам исходного объекта:
<div><label>PropertyX:</label><input data-src="propertyX"></input></div>
  • после нажатия кнопки edit , получение соответствующих данных строки, заполнение всплывающего окна редактора <input> поля с этими данными, передайте anchoОт r до отредактированной строки (rowindex значение атрибута) до всплывающего атрибута:
//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> в объекте:
const modifiedData = {};
$.each($('#editform input'), function(){
  Object.assign(modifiedData, {[$(this).attr('data-src')]:$(this).val()});
});
  • POST данных (вместе с соответствующими rowindex) на сервер и перезагрузка (ajax.reload()) актуальных данных при успешном завершении:
$.ajax({
    url: '/editrow',
    method: 'POST',
    data: {id: $('#editform').attr('rowindex'), ...modifiedData},
    success: () => {
        $('#editform').modal('hide');
        dataTable.ajax.reload();
    }
});

Завершите живую демонстрацию этого метода, который вы можете проверить в DevTools вашего браузера по следующей ссылке с некоторым бонусом в виде строки кнопка удаления .

Пример кода HTML и jQuery может выглядеть следующим образом ( не исполняемый , поскольку отсутствует вспомогательный бэкэнд):

$(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>
2 голосов
/ 03 июля 2019

Если вы имеете в виду JQUERY DATATABLE , тогда вы можете вставлять поля ввода (которые все еще сохраняют данные ячейки) для каждого столбца в строке таблицы по своему желанию и устанавливать границы поля ввода так, чтобы они не отображались., с css.

ТАБЛИЦА ПРИМЕРОВ

 <style>
  .no-input-border {
    border: 'none' !important; background: 'none' !important;
   }
 </style>
 <table id="dynamic_table">
   <thead>
     <tr>
       <th>Name</th>
       <th>State</th>
       <th>Address</th>
       <th>Active</th>
       <th>Action</th> <!-- This column would hold your buttons -->
     </tr>
   </thead>
   <tbody>
   </tbody>
</table>

ПРИМЕР ИСПОЛЬЗОВАНИЯ ДАННЫХ

 var table = $('#dynamic_table').DataTable({
          "order":[[ 0, 'asc' ]], // order by first column
          "processing": true,
          'paging': true,
          'searching': true,
          'retrieve': true,
          'serverSide': true,
          'ajax': {
              'url': "your-ajax-url",
              'type': 'POST'
          },
          'columns': [ //every **name:** value must be present in your json
              { data: null, name: 'name'},
              { data: null, name: 'state' },
              { data: null, name: 'address' },
              { data: null, name: 'active' },
              { data: null, name: 'id' } // column that holds your buttons
          ],
          "columnDefs": [
             {
                "targets": 0,  // column that inserts an input field
                "data":  'name',
                "orderable": false,
                "createdCell": function (td, cellData, rowData, row, col){
                  return '<input type="text" class="no-input-border" name="name" value="'+cellData+'" />'
                }
             },
             {
                "targets": 1,  // column that inserts an input field
                "data":  'state',
                "orderable": false,
                "createdCell": function (td, cellData, rowData, row, col){
                  return '<input type="text" class="no-input-border" name="state" value="'+cellData+'" />'
                }
             },
             {
                "targets": 2,  // column that inserts an input field
                "data":  'address',
                "orderable": false,
                "createdCell": function (td, cellData, rowData, row, col){
                  return '<input type="text" class="no-input-border" name="state" value="'+cellData+'" />'
                }
             },
             {
                "targets": 3,  // column that inserts an input field
                "data":  'active',
                "orderable": false,
                "createdCell": function (td, cellData, rowData, row, col){
                  return '<input type="text" class="no-input-border" name="active" value="'+cellData+'" />'
                }
             },
             {
                "targets": 4,  // column that holds your buttons
                "data":  'id',
                "orderable": false,
                "createdCell": function (td, cellData, rowData, row, col){
                  return '<button class="edit_row">Edit<button>'
                }
             }
          ],
          'responsive': true,
          'initComplete': function(settings, json) {
            //Run a function when table first initializes
          },
          'drawCallback': function( settings ) {
            //Run a function anytime table reloads when paginating
          }
      });

ПРИМЕР ДАННЫХФУНКЦИЯ РЕДАКТИРОВАНИЯ СТРОКИ

$('#dynamic_table tbody').on('click', '.edit_row', function () {
  var row = table.row( $(this).parents('tr') ); // row that was clicked
  var d = row.data(); // data of the row button that was clicked .eg. console.log(d.name)
  var index = row.index();
  var json = { // json to be sent
        id: d.id,
        name: table.cell(index,0).nodes().to$().find('input').val(),
        state: table.cell(index,1).nodes().to$().find('input').val(),
        address: table.cell(index,2).nodes().to$().find('input').val(),
        active: table.cell(index,3).nodes().to$().find('input').val()
   }
  /*Your Ajax Function Here*/
});

ПЕРЕЗАГРУЗИТЬ ФУНКЦИЮ, ОБРАЩАЮЩУЮСЯ К ДАННЫМ

table.ajax.reload( function ( json ) {
  //Run function after table reloads
});  
0 голосов
/ 01 июля 2019

Вы можете создать пользовательскую кнопку в datatable.Вы можете перейти к этой документации , чтобы узнать, как она работает.Теперь в действии вы можете вызвать некоторую функцию внутри него, когда пользователь щелкнет по нему, кнопка вызовет функцию в javascript и сделает то, что вы хотите внутри нее.

Вот пример кода.

$('#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)
        }
    });

    },
   buttons: [
    { text: 'Add', name: 'btnAdd', action: function ( e, dt, node, config ) {
                $.fn.addfunction();
            }},
    { extend: 'selected', text: 'Edit', name: 'btnEdit', action: function ( e, dt, node, config ) {
                $.fn.editfunction();
            }},
    { extend: 'selected',  text: 'Delete', name: 'btnDelete', action: function ( e, dt, node, config ) {
                $.fn.deletefunction();
            }},
   ],
   "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"
     },

    ]
});

$.fn.addfunction = function(){
//Your code here
}

$.fn.editfunction = function(){
//Your code here
}

$.fn.deletefunction = function(){
//Your code here
}

Я добавил идею этого документа из таблиц данных , которые создают пользовательскую кнопку, а также создают и вызывают функцию в jquery

Есть и другой способ использования и присвоения идентификатора длякнопка.Вот пример:

$('#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)
            }
        });

        },
       buttons: [
        { text: 'Add', name: 'btnAdd', 
        attr:{
         id: 'btnAdd'
        }},
        { extend: 'selected',  text: 'Edit', name: 'btnEdit', 
        attr:{
         id: 'btnEdit'
        }},
        { extend: 'selected',  text: 'Delete', name: 'btnDelete', 
        attr:{
         id: 'btnDelete'
        }},
       ],
       "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"
        },

       ]
    });

    $(document).on('click', '#btnAdd', function(e)
        {
          e.preventDefault();
          e.stopPropagation();
          //your code here
        });

    $(document).on('click', '#btnEdit', function(e)
        {
          e.preventDefault();
          e.stopPropagation();
          //your code here
        });

    $(document).on('click', '#btnDelete', function(e)
            {
              e.preventDefault();
              e.stopPropagation();
              //your code here
            });

Извините за многие Редактировать Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...