Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background color in Yii2 gridview cell depend on its value

Tags:

gridview

yii2

I am trying to make background color that depending on the value calculation number in one cell. This is my code:

[
'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'],
        ],

but i got an error, that say "Cannot use object of type yii\data\ActiveDataProvider as array"

So, How can i change the background gridview cell that have value from some calculation ?

like image 343
Galang Re Avatar asked Sep 13 '16 04:09

Galang Re


2 Answers

Use 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')];
    },
],
like image 137
Bizley Avatar answered Oct 12 '22 11:10

Bizley


Use the rowOptions and change the value of class to change the color.

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

This will generate an output like the following:

output

like image 39
Carlos Carvalho Avatar answered Oct 12 '22 12:10

Carlos Carvalho