How to create dynamic columns and trouble fixedColumns
How to create dynamic columns and trouble fixedColumns
1) The aim of the work: the user fills in the report in which a different number of fields,each field you want to display in the table as a separate column.How can I do it better?
2) the goal of the work: Since there will be a different number of columns,the column with actions(the last one) should be attached to the right side,but it has a scroll that should not appear.
I believe that the second error follows from the first one, since I am new to programming and this library is still difficult for me,I did not find any other choice,as shown in the pictures.
If you need a code, I'll send it.
3)I also think that the problem with duplicate sorting is related to the first problem.
P. S I use bootstrap 4
$.ajax({
url: '../../../assets/php/data_report.php',
type: 'POST',
dataType: 'json',
data: {
json: localStorage.getItem('info_reports')
},
success: function (data) {
let array = data;
array.forEach(e => {
if (e === 'id') {
$('.data-report').find('thead').find('tr').append(
`<th class="text-center align-baseline">${e}</th>`
)
} else {
$('.data-report').find('thead').find('tr').append(
`<th class="text-center align-baseline vis-tabs">${e}</th>`
);
}
});
$('.data-report').find('thead').find('tr').append(
`<th class="text-center align-baseline not-visable" style:"width:100%;"></th>`
);
$.each($('.data-report').find('thead').find('tr').find('th').toArray(), function (i, v) {
countRows.push($(this).index());
if ($(this).index() !== 1 || $(this).index() !== 2 || $(this).index() !== 3) {
offSrchOrdbl.push($(this).index());
}
console.log(offSrchOrdbl);
});
table_report = $('.data-report').DataTable({
"pagingType": "full_numbers",
// responsive: true,
scrollX: true,
scrollY: 200,
scrollCollapse: true,
/* paging: false, */
fixedColumns: true,
fixedColumns: {
leftColumns:0,
rightColumns:1,
},
dom: 'Bfrtip',
"processing": true,
"serverSide": true,
"ajax": "../../../assets/php/data_report_json.php",
lengthMenu: [
[10, 25, 50, -1],
['10 строк', '25 строк', '50 строк', 'Показать все']
],
// select:{
// style:'os',
// selector:'td:not(:last-child)'
// },
"language": {
"paginate": {
"first": "Первая",
"previous": "Предыдущая",
"next": "Следующая",
"last": "Последняя"
},
"aria": {
"sortAscending": ": активировать для сортировки столбца по возрастанию",
"sortDescending": ": активировать для сортировки столбца по убыванию"
},
"select": {
"rows": {
"_": "Выбрано записей: %d",
"0": "Кликните по записи для выбора",
"1": "Выбрана одна запись"
}
},
"processing": `<div class="preloader" id="page-preloader">
<div class="loader_one">
<div class="loader_two"></div>
</div>
</div>`,
"search": "Поиск:",
"lengthMenu": "Показать _MENU_ записей",
"info": "Записи с _START_ до _END_ из _TOTAL_ записей",
"infoEmpty": "Записи с 0 до 0 из 0 записей",
"infoFiltered": "(отфильтровано из _MAX_ записей)",
"infoPostFix": "",
"loadingRecords": "Загрузка записей...",
"zeroRecords": "Записи отсутствуют.",
"emptyTable": "В таблице отсутствуют данные",
buttons: {
pageLength: {
_: "Показать %d строк"
}
}
},
"columnDefs": [
// {
// "defaultContent": "<b class='red'>не указано<i></i></b>",
// "targets": countRows
// },
{
"targets": [0],
// visible: false,
"orderable": false,
"searchable": false,
},
// {
// "targets": offSrchOrdbl,
// "orderable": false,
// "searchable": false,
// },
{
"title": "Действие",
"targets": -1,
"orderable": false,
"searchable": false,
"className": "text-center",
render: function (data) {
return `
<div class="d-flex justify-content-center">
<button class="btn btn-sm btn-outline-success view-rep mr-50">Просмотр</button>
<button class="btn btn-sm btn-outline-danger clear-rep">Очистка</button>
</div>
`;
},
}
],
buttons: [
{
extend: 'pageLength',
},
{
extend: 'excel',
extension: '.xlsx',
exportOptions: {
columns: ".vis-tabs",
}
}]
});
},
error: function (data) {
Toast.fire({
icon: 'error',
title: 'Ошибка инициализации',
onAfterClose: (toast) => {
// $(location).attr('href','history_reports.php');
}
})
}
});
<div class="col-12">
<div class="card">
<div class="card-body col-12 mx-auto">
<div class="card-content">
<div class="row d-flex justify-content-center col-11 mx-auto">
<table class="mx-auto table table-striped table-bordered data-report" style="width:100%">
<thead>
<tr></tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Answers
You need to define the columns - at the moment you have just a single column defined in your DataTable (both from
columnDefs
and also thethead
).What does
report_data.php
return please? Is it the full data for the table, or something else?Allan
Thank you Allon for not staying away. This file returns static column names (id, name, role, etc.).
Can this be done without writing the code to manually add thead, etc.?
If you want to be able to define the columns by the Ajax loaded data, you need to get the column information first and then load the DataTable. This FAQ covers that.
Allan