【问题标题】:Adding an expression in htmlOptions of CGridView在 CGridView 的 htmlOptions 中添加表达式
【发布时间】:2012-05-08 17:54:57
【问题描述】:

我正在尝试使用数组中的值设置 htmlOptions,该数组用作 CGridView 组件的 DataProvider(它是 CArrayDataProvider)。其中有一个标志,可以是 0 或 1(0 表示字体粗细:正常,1 表示粗体)

'htmlOptions'=>array('style'=>'$data["flag"] == 1 ? font-weight: bold; : font-weight: normal;'),

没用,所以我尝试直接在DataProvider中设置样式(返回font-weight:bold;或者font-weight:normal;):

'htmlOptions'=>array('style'=>'$data["style"]'),

但是输出是:

<td style="$data["style]">Value</td>

我做错了什么?

【问题讨论】:

    标签: php yii yii-components


    【解决方案1】:

    您不能在htmlOptions 中使用$data 或$row。你必须扩展CDataColumn

    请参阅this article 了解如何操作。

    【讨论】:

    • 这对我帮助很大,但是如果我想设置一些固定的样式加上一些动态的怎么办。我尝试连接一些字符串,但没有成功。
    【解决方案2】:

    Yii v1.1.13 现在在 CGridView 中内置了这个功能: http://www.yiiframework.com/doc/api/1.1/CGridView#rowHtmlOptionsExpression-detail

    您可以使用 $data 作为模型,使用 $row 作为行号来评估字符串中的 htmlOptions 数组。由于语法有点奇怪,我将展示一个示例:

    $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.\'"
                      )')
     );
    

    请注意,htmlOptions 的 php 数组位于字符串中。这很奇怪,但它就是这样工作的!

    【讨论】:

    • 非常好用又好用
    【解决方案3】:

    htmlOptions 无权访问 $data。 所以你可以试试这个

    'value' => '($data["flag"] == 1 ? "<b>$data->your_value</b> ":"$data->your_value")',
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多