Skip to content
Advertisement

Set background color attribute for single cell with Laravel DataTables

I’m using Yajra Laravel Datatables for my data display with serverside ajax loads, to prevent long loads on large amounts.

Now I want to color single TD in a row depending on the status (and other options)

I found that I can easily add parametes to the whole row, depending on options:

->setRowAttr([
    'style' => function($item){
        return $item->disabled ? 'background-color: #ff0000;' : 'background-color: #00ff00;';
    }
])

And this produces me:

enter image description here

But I don’t need to color the whole row, only the Bookings TD (in this case) since a different color will be applied for the Active statuses + another one for Room groups, like this:

enter image description here

How can this be accomplished?

PS: I’m using Laravel 5.3 with Datatavles 6

Advertisement

Answer

Ok, solved this myself after reading this documentation
http://datatables.net/release-datatables/examples/advanced_init/row_callback.html:

First I added additional columns before Datatables make() call, since the original get overwritten with language outputs, like this:

->addColumn('active', function ($item) {
    return $item->disabled ? 0 : 1;
})
->editColumn('disabled', function ($item) {
    $item->disabled ? t('No') : t('Yes');
})

Then I added check to JS part right after data call:

serverSide: true,
ajax: {
    url: ...,
    type: "get"
},
columns: [
    ...
    {data: 'disabled', name: 'disabled'},
    ...
],
createdRow: function ( row, data, index ) {
    ...
    if ( data['active'] == 1 ) {
        $('td', row).eq(5).addClass('success');
    } else {
        $('td', row).eq(5).addClass('danger');
    }
    ...
},
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement