Search code examples
gridviewyii2yii2-basic-app

Yii2 Color of gridview cells, compare date condition


[
            'attribute' => 'duedate',
            'contentOptions' => function ($model, $key, $index, $column) {
                $time = new \DateTime('now');
                $today = $time->format('Yyyy-mm-dd');
                return ['style' => 'background-color:' 
                    . ($model->duedate < $today ? 'red' : 'white')];
            },
        ],

I use this code to show if the date is overdue is will has red background color and white if not.

But it all show red. Please help me.

Thank you.


Solution

  • You are getting current date in wrong format,

    Just change your code like

    [
         'attribute' => 'duedate',
         'contentOptions' => function ($model, $key, $index, $column) {
           $time = new \DateTime('now');
           $today = $time->format('Y-m-d H:i:s');
           return ['style' => 'background-color:' 
                        . (strtotime($model->duedate) < strtotime($today) ? 'red' : 'white')];
         },
    ],