Yii2:contentOptions(GridView)中的动态样式

Ant*_*pez 3 gridview yii2

在Yii2中有更优雅的动态样式方法:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        [
           'attribute' => 'fecha',
           'contentOptions' => ['style' => 'color: '.$dataProvider->models[0]->fechaVerif->color],
        ],

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
Run Code Online (Sandbox Code Playgroud)

一边使用匿名功能?我尝试过类似的东西:

'contentOptions' => ['style' => 'color: '. fechaVerif.color]
Run Code Online (Sandbox Code Playgroud)

但它显然没有用.

Lat*_*try 7

查看Yii2中的Column :: renderDataCell实现:

public function renderDataCell($model, $key, $index)
{
    if ($this->contentOptions instanceof Closure) {
        $options = call_user_func($this->contentOptions, $model, $key, $index, $this);
    } else {
        $options = $this->contentOptions;
    }
    return Html::tag('td', $this->renderDataCellContent($model, $key, $index), $options);
}
Run Code Online (Sandbox Code Playgroud)

因此,做你想做的事的唯一方法是:

            [
                'attribute' => 'fecha',
                'contentOptions' => function($model)
                    {
                        return ['style' => 'color:' . $model->fechaVerif->color];
                    }
            ],
Run Code Online (Sandbox Code Playgroud)