Change background color in Yii2 gridview cell depend on its value
Asked Answered
D

3

10

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 ?

Dodecasyllable answered 13/9, 2016 at 4:20 Comment(0)
F
9

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')];
    },
],
Flagellum answered 13/9, 2016 at 5:19 Comment(0)
B
1

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

Brunhilda answered 19/5, 2018 at 14:21 Comment(0)
F
0

rowOptions add in Gridview

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'rowOptions' => function($model, $key, $index, $column){
        if($index % 2 == 1){
            return ['class' => 'info'];
        }
    },
    'columns' => [
    .........
Foliate answered 26/7, 2023 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.