Reinitializing DataTable to use Buttons

Reinitializing DataTable to use Buttons

DevMushrefDevMushref Posts: 10Questions: 4Answers: 0

I get an error when I try to execute the code, "Cannot reinitialize DataTable". I checked the docs of DataTable saying I should either destroy() the datatable or include the code within the original DataTable object. This cannot be done since I'm using Yajra DataTable (Laravel package PHP datatable wrapper). I tried adding table.destroy() in all possible places but not working.

How can I $.extend() or reinitialize the Yajra datatable in order to use the below function?

"use strict";


// Class definition
var KTDatatablesExample = function () {
    // Shared variables
    var table;
    var datatable;

    // Private functions
    var initDatatable = function () {
        // Set date data order
        const tableRows = table.querySelectorAll('tbody tr');

        tableRows.forEach(row => {
            const dateRow = row.querySelectorAll('td');
            const realDate = moment(dateRow[3].innerHTML, "DD MMM YYYY, LT").format(); // select date from 4th column in table
            dateRow[3].setAttribute('data-order', realDate);
        });

        // Init datatable --- more info on datatables: https://datatables.net/manual/
        datatable = $(table).DataTable({
            "info": false,
            'order': [],
            'pageLength': 10,
        });
    }

    // Hook export buttons
    var exportButtons = () => {
        const documentTitle = 'Incidents List';
        var buttons = new $.fn.dataTable.Buttons(table, {
            buttons: [
                {
                    extend: 'copyHtml5',
                    title: documentTitle
                },
                {
                    extend: 'excelHtml5',
                    title: documentTitle
                },
                {
                    extend: 'csvHtml5',
                    title: documentTitle
                },
                {
                    extend: 'pdfHtml5',
                    title: documentTitle
                }
            ]
        }).container().appendTo($('#incident_datatable_export_buttons'));

        // Hook dropdown menu click event to datatable export buttons
        const exportButtons = document.querySelectorAll('#incident_datatable_export_menu [data-kt-export]');
        exportButtons.forEach(exportButton => {
            exportButton.addEventListener('click', e => {
                e.preventDefault();

                // Get clicked export value
                const exportValue = e.target.getAttribute('data-kt-export');
                const target = document.querySelector('.dt-buttons .buttons-' + exportValue);

                // Trigger click event on hidden datatable export buttons
                target.click();
            });
        });
    }

    // Search Datatable --- official docs reference: https://datatables.net/reference/api/search()
    var handleSearchDatatable = () => {
        const filterSearch = document.querySelector('[data-kt-filter="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            datatable.search(e.target.value).draw();
        });
    }

    // Public methods
    return {
        init: function () {
            table = $('#reports-table').DataTable();

            if ( !table ) {
                return;
            }

            initDatatable();
            exportButtons();
            handleSearchDatatable();

        }
    };
}();

// On document ready
KTUtil.onDOMContentLoaded(function () {
    KTDatatablesExample.init();
});


// $.extend($.fn.datatable.defaults, {
//     serverSize: false
// });

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,599

    Probably the easiest way would be to add destroy to the configuration options. If that doesn't help, we're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • DevMushrefDevMushref Posts: 10Questions: 4Answers: 0

    Hello Dear Colin,
    I can share url yet as the code is not published. As well as JS Bin since I'm using Yajra Datatables

    Yajra is the one intitilizing the datatable using this PHP method:

    public function html()
        {
            return $this->builder()
                ->setTableId('reports-table')
                ->columns($this->getColumns())
                ->minifiedAjax()
                ->dom('t') // <"d-flex" Br> <ft> <"d-flex justify-content-between" lip>
                ->stateSave(true)
                ->responsive(true)
                ->autoWidth(true)
                ->parameters([
                    'scrollX' => false,
                    'lengthMenu' => [
                        [10, 25, 50, 100, -1],
                        ['10 rows', '25 rows', '50 rows', '100 rows', 'Show all']
                    ],
    
                ])
                ->addTableClass('table align-middle table-row-dashed fw-bold fs-5 text-gray-600');
        }
    

    I tried adding ->destroy(true) which I believe is working. But, when I type into the search, the data vanish and never renders again until I refresh.

    I am trying to redraw the destroyed data again using the posted code above.

  • kthorngrenkthorngren Posts: 21,186Questions: 26Answers: 4,925

    If your goal is to add the buttons to the Datatables initialization using. destroy or destroy() is not going to help. I'm not familiar with Yarja Datatables but here is the Buttons docs. Since this is created by a third party your best option is to get help from Yarja's developers.

    Kevin

Sign In or Register to comment.