Adding an expression in htmlOptions of CGridView
-
06-06-2021 - |
質問
I'm trying to set the htmlOptions using a value from the array used as DataProvider of the CGridView component (it's a CArrayDataProvider). In it there is a flag that will be either 0 or 1 (0 for font-weight: normal and 1 for bold)
'htmlOptions'=>array('style'=>'$data["flag"] == 1 ? font-weight: bold; : font-weight: normal;'),
It didn't work, so I tried to set the style directly in the DataProvider (returning font-weight: bold; or font-weight: normal;):
'htmlOptions'=>array('style'=>'$data["style"]'),
But the output is:
<td style="$data["style]">Value</td>
What am I doing wrong?
解決
You can't use $data
or $row in htmlOptions
. You have to extend the CDataColumn
.
Refer to this article for information on how to do it.
他のヒント
Yii v1.1.13 now has this functionality built into CGridView: http://www.yiiframework.com/doc/api/1.1/CGridView#rowHtmlOptionsExpression-detail
You can use $data for the model and $row for the row number to evaluate an htmlOptions array from a string. Since the syntax is a little weird I'll show an example:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $dataProvider,
'columns' => array(
'columns' => array(
array(
'name'=>'Column Name 1',
"value"=>'$data->colVal',
),
'name'=>'Column Name 2',
"value"=>'$data->colExpression()',
),
"modelAttributeUsingNameLabel",
),
"rowHtmlOptionsExpression"=>'array(
"onclick"=>
"window.location = \'.$this->url.\'"
)')
);
Notice that the php array for the htmlOptions is in a string. That is strange, but it is how it works!
htmlOptions has no access to $data. So you can try this
'value' => '($data["flag"] == 1 ? "<b>$data->your_value</b> ":"$data->your_value")',