Search code examples
datatablesfilteringadminlte

Filtering columns in Datatables as used in AdminLTE


I'm building a Laravel app with AdminLTE integrated in the backend. AdminLTE uses DataTables to generate the tables, this works fine. But in AdminLTE it's only possible to sort columns, and it's not possible to filter columns. In one admin view I want to filter columns with a dropdown as shown in this DataTables example. I've tried to integrate the example code in AdminLTE main.js. But I haven't got it working. In main.js there is a codesnippet where probably the new code should or could be integrated.

$('.datatable').each(function () {
    if ($(this).hasClass('dt-select')) {
        window.dtDefaultOptions.select = {
            style: 'multi',
            selector: 'td:first-child'
        };

        window.dtDefaultOptions.columnDefs.push({
            orderable: false,
            className: 'select-checkbox',
            targets: 0
        });
    }
    $(this).dataTable(window.dtDefaultOptions);

});

Does anyone have an idea how to get the filtering working?


Solution

  • The extra code has to be added in main.js as below. In my case I've put the filter in the header of the second column (the first column is the checkbox) and put a text on the first row of the select dropdown for extra information to the user.

    $('.datatable').each(function () {
            if ($(this).hasClass('dt-select')) {
                window.dtDefaultOptions.select = {
                    style: 'multi',
                    selector: 'td:first-child'
                };
    
                window.dtDefaultOptions.columnDefs.push({
                    orderable: false,
                    className: 'select-checkbox',
                    targets: 0
                });
    
                window.dtDefaultOptions.initComplete = function () {
                    this.api().columns('1').every( function () {
                        var column = this;
                        var select = $('<select><option value="">Filter this column</option></select>')
                            .appendTo( $(column.header()).empty() )
                            .on( 'change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );
    
                                column
                                    .search( val ? '^'+val+'$' : '', true, false )
                                    .draw();
                            } );
    
                        column.data().unique().sort().each( function ( d, j ) {
                            select.append( '<option value="'+d+'">'+d+'</option>' )
                        } );
                    } );
                }
            }
            $(this).dataTable(window.dtDefaultOptions);