在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]
但它显然没有用.
解决方法
查看Yii2中的Column :: renderDataCell实现:
public function renderDataCell($model,$key,$index) { if ($this->contentOptions instanceof Closure) { $options = call_user_func($this->contentOptions,$model,$index,$this); } else { $options = $this->contentOptions; } return Html::tag('td',$this->renderDataCellContent($model,$index),$options); }
因此,做你想做的事的唯一方法是:
[ 'attribute' => 'fecha','contentOptions' => function($model) { return ['style' => 'color:' . $model->fechaVerif->color]; } ],