Yii - CGridView - 添加自己的属性

Dir*_*ust 5 php yii

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'title',          // display the 'title' attribute
        'category.name',  // display the 'name' attribute of the 'category' relation
        'content:html',   // display the 'content' attribute as purified HTML
        array(            // display 'create_time' using an expression
            'name'=>'create_time',
            'value'=>'date("M j, Y", $data->create_time)',
        ),
        array(            // display 'author.username' using an expression
            'name'=>'authorName',
            'value'=>'$data->author->username',
//HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              'htmlOptions'=>array('class'=>'$data->author->username', 'secondAttribute' => $data->author->id),
//HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        ),
        array(            // display a column with "view", "update" and "delete" buttons
            'class'=>'CButtonColumn',
        ),
    ),
));
Run Code Online (Sandbox Code Playgroud)

在选项中value我可以从PHP添加变量,但是对于选项,htmlOptions这是不可能的.为什么?
如何使用PHP变量创建属性?

Jon*_*Jon 9

columns未指定class属性的情况下在集合中添加数组时,正在创建的列的类型为CDataColumn.该物业CDataColumn::value明确记录

将为每个数据单元计算的PHP表达式,其结果将呈现为数据单元格的内容.

因此,value具有eval为每一行获取的特殊属性,这就是您可以"动态"设置它的原因.然而,这是一个例外,几乎没有其他任何东西支持相同的功能.

但是,你很幸运,因为该属性cssClassExpression是另一个特殊的例外,它恰好涵盖了这个用例.所以你可以这样做:

array(
    'name'=>'authorName',
    'value'=>'$data->author->username',
    'cssClassExpression' => '$data->author->username',
),
Run Code Online (Sandbox Code Playgroud)

编辑:我从你的例子中复制/粘贴时犯了一个错误,并没有注意到你正在尝试对内部的其他属性做同样的事情htmlOptions(我现在已经删除了代码的相关部分).

如果您需要为动态值添加更多选项,您别无选择,只能子类化CDataColumn并覆盖该renderDataCell方法(库存实现在此处).


Bli*_*izz 5

不知道这是否仍然适用(假设有一个已接受的答案),但是以"rowHtmlOptionsExpression"的形式有一个稍好的解决方案.这指定了将为每一行计算的表达式.如果eval()调用的结果是一个数组,它将被用作<tr>标记的htmlOptions.所以你现在基本上可以使用这样的东西:

$this->widget('zii.widgets.grid.CGridView', array
(
   ...
   'rowHtmlOptionsExpression' => 'array("id" => $data->id)',
   ...
Run Code Online (Sandbox Code Playgroud)

你的所有标签都有一个带有记录'PK的id属性.只需稍微修改jQuery以从该标记获取id而不是额外的列,您应该进行设置.