How to create dynamic columns and trouble fixedColumns

How to create dynamic columns and trouble fixedColumns

XanaxLolXanaxLol Posts: 3Questions: 1Answers: 0

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

  • allanallan Posts: 63,471Questions: 1Answers: 10,467 Site admin

    You need to define the columns - at the moment you have just a single column defined in your DataTable (both from columnDefs and also the thead).

    What does report_data.php return please? Is it the full data for the table, or something else?

    Allan

  • XanaxLolXanaxLol Posts: 3Questions: 1Answers: 0

    Thank you Allon for not staying away. This file returns static column names (id, name, role, etc.).

    <?php
        session_start();
        require_once('mysql.php');
    
        $report_id = json_decode($_POST['json'], true)[0][0];
        
        $_SESSION['report']['id'] = $report_id;
    
        $sql = 'SELECT fields FROM reports WHERE id = ?';
        $select = $pdo->prepare($sql);
        $select->execute( [$report_id] );
        $from_reports = $select->fetch(PDO::FETCH_ASSOC);
    
        // $from_reports = mysqli_fetch_assoc(mysqli_query($mysql, "SELECT `fields` FROM `reports` WHERE `id` = '$report_id'"));
        // $from_filled_reports = mysqli_fetch_all(mysqli_query($mysql, "SELECT `filled_fields`, (SELECT firstname from users WHERE users.id = filled_reports.id_user), (SELECT lastname from users WHERE users.id = filled_reports.id_user) FROM `filled_reports` WHERE `id_report` = '$report_id'"));
    
        $first = ['id', 'ФИО', 'Название организации', 'Название отдела', 'Роль', 'Телефон', 'Дата ввода информации'];
    
        $fields = json_decode($from_reports['fields'], true);
    
        foreach ($fields as $field) {
            array_push($first, $field["name_pole"]);
        }
        
        echo json_encode($first);
    

    Can this be done without writing the code to manually add thead, etc.?

    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);
    
  • allanallan Posts: 63,471Questions: 1Answers: 10,467 Site admin

    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

This discussion has been closed.