Yii2:contentOptions(GridView)中的动态样式
Yii2: dynamic style in contentOptions (GridView)
在 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]
但显然没用
查看 Column::renderDataCell Yii2 中的实现:
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];
}
],
在 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]
但显然没用
查看 Column::renderDataCell Yii2 中的实现:
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];
}
],