使用Laravel DataTables设置单个单元格的背景颜色属性

时间:2017-06-09 11:28:01

标签: php laravel datatables laravel-5.3

我正在使用Yajra Laravel Datatables进行数据显示,并使用服务器端ajax加载,以防止大量长时间负载。

现在我想根据状态(和其他选项)连续为单个TD着色

我发现我可以轻松地将参数添加到整行,具体取决于选项:

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

这就产生了我:

enter image description here

但是我不需要为整行划线,只需要预订TD(在这种情况下),因为不同的颜色将应用于活动状态+另一个用于房间组,如下所示:

enter image description here

如何实现这一目标?

PS:我正在使用Laravel 5.3和Datatavles 6

2 个答案:

答案 0 :(得分:3)

好的,在阅读本文档后自己解决了这个问题 的 http://datatables.net/release-datatables/examples/advanced_init/row_callback.html

首先我在Datatables make()调用之前添加了其他列,因为原来被语言输出覆盖了,如下所示:

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

然后我在数据通话后立即将检查添加到JS部分:

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');
    }
    ...
},

答案 1 :(得分:-1)

请参考

php:

DataTables::of($query)
->addColumn('stylesheet', function ($record) {
                                return [
                                    [
                                        'col' => 11,
                                        'style' => [
                                            'background' => '#080',
                                        ],
                                    ],
                                    [
                                        'col' => 12,
                                        'style' => [
                                            'background' => '#c00',
                                            'color' => '#fff',
                                        ],
                                    ],
                                ];
                            });

javascript:

DataTable({
columns: [...],
createdRow: function (row, data, dataIndex, cells) {
                if (data.stylesheet) {
                    $.each(data.stylesheet, function (k, rowStyle) {
                        $(cells[rowStyle.col]).css(rowStyle.style);
                    });
                }
            },
})

结果: enter image description here