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

时间:2015-03-12 15:05:28

标签: 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'],
    ],
]); ?>

除了使用匿名函数?我试过像:

'contentOptions' => ['style' => 'color: '. fechaVerif.color]

但它显然没有用。

1 个答案:

答案 0 :(得分: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);
}

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

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