Search code examples
javascriptlaravel-5yajra-datatable

Correct way to check if yajra/laravel table was already initialized?


In use laravel 5.7 / jquery 3 / blade app I use yajra/laravel-datatables-oracle 8 and open it in modal dialog and I open this dialog for the 2nd/3rd time I got warning message :

DataTables warning: table id=get-fee-dt-listing-table - Cannot reinitialise DataTable

In blade file :

<div class="modal-body">

    <div class="table-responsive dataTables_header">
        <table class="table table-bordered table-striped text-primary" id="get-fee-dt-listing-table">
            <thead>
            <tr>
                <th></th>

and in .js file:

bookingsAndAvailability.prototype.showFeesSelection = function () {
    console.log('showFeesSelection::')
    $("#div_check_in_fees_modal").modal({
        "backdrop": "static",
        "keyboard": true,
        "show": true
    });



    // var dtListingTable= document.getElementById('get-fee-dt-listing-table')
    // dtListingTable  = null // If to uncomment these 2 lines - they do not help

    $("#get-fee-dt-listing-table").html('') // // If to uncomment these 2 lines - they do not help

    oTable = $('#get-fee-dt-listing-table').DataTable({
        processing: true,
        language: {
            "processing": "Loading fees..."
        },

I close the modal with command :

$("#div_check_in_fees_modal").modal('hide');

which is correct way to check if table was already initialised?

Thanks!


Solution

  • You can use $.fn.dataTable.isDataTable() for this.

    From the docs:

    This method provides the ability to check if a table node is already a DataTable or not. This can be useful to ensure that you don't re-initialise a table that is already a DataTable.

    Please note that this is a static function and is accessed through the $.fn.dataTable object, not an API instance. It can be accessed at any time, even before any DataTables have been created on the page.

    if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
      $('#example').dataTable();
    }
    

    In your case it would be something like this:

    if (! $.fn.DataTable.isDataTable('#get-fee-dt-listing-table')) {
        oTable = $('#get-fee-dt-listing-table').DataTable({
            processing: true,
            language: {
                "processing": "Loading fees..."
            },
        ...
    }