更改Yii2 gridview单元格中的背景颜色取决于其值

时间:2016-09-13 04:20:01

标签: gridview yii2

我正在尝试根据一个单元格中的值计算数量来制作背景颜色。这是我的代码:

[
'attribute' => 'coefTK',
'label' => '<abbr title="Koefisien Jumlah Tenaga Kerja">TK</abbr>',
'encodeLabel' => false,
'headerOptions' => ['style'=>'text-align:center'],
'options' => [ 'style' => $dataProvider['coefTK']/$dataProvider['coefTK_se']<2 ? 'background-color:red':'background-color:blue'],
        ],

但我收到错误,说“不能使用yii \ data \ ActiveDataProvider类型的对象作为数组”

那么,我如何更改具有某些计算值的背景gridview单元格呢?

2 个答案:

答案 0 :(得分:5)

使用contentOptions

[
    'attribute' => 'coefTK',
    'label' => '<abbr title="Koefisien Jumlah Tenaga Kerja">TK</abbr>',
    'encodeLabel' => false,
    'headerOptions' => ['style'=>'text-align:center'],
    'contentOptions' => function ($model, $key, $index, $column) {
        return ['style' => 'background-color:' 
            . (!empty($model->coefTK_se) && $model->coefTK / $model->coefTK_se < 2
                ? 'red' : 'blue')];
    },
],

答案 1 :(得分:0)

使用rowOptions并更改class的值以更改颜色。

'rowOptions' => function($model, $key, $index, $column){
    if($index % 2 == 0){
        return ['class' => 'info'];
    }
},

这将生成如下输出:

output

相关问题