如何向CGridView添加按钮?

cod*_*ama 3 yii cgridview cbuttoncolumn

听起来很简单吧?我搜索了高低,我无法找到如何做到这一点.我有一个CGridView:

$dataProvider = new CArrayDataProvider ($auctions);
$this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider'=>$dataProvider,
  'columns'=>array(
    'id::ID',
    'product.title::Title',
    'state::Status',
  ),
));
Run Code Online (Sandbox Code Playgroud)

我想添加第四列,只包含一个简单的按钮,按下时将执行javascript.我试过了:

array(
  'class' => 'CButtonColumn',
),
Run Code Online (Sandbox Code Playgroud)

这只是给我一个错误:

Undefined property: stdClass::$primaryKey
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Riz*_*han 8

试试这个:

$dataProvider = new CArrayDataProvider ($auctions);
$this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider'=>$dataProvider,
  'columns'=>array(
    'id::ID',
    'product.title::Title',
    'state::Status',
     array(
         'type' => 'raw',
         'value' => '<button onclick=\'alert("It works!")\' value="clickme"/>'
     )
  ),
));
Run Code Online (Sandbox Code Playgroud)


小智 7

最好的方法是使用CButtonColumn :: template和CButtonColumn ::按钮.

array(
    'class' => 'CButtonColumn',
    'template' => '{view} {update} {delete} {copy}',
    'buttons'=>array(
        'copy' => array(
            'label'=>'Copy', // text label of the button
            'url'=>"CHtml::normalizeUrl(array('copy', 'id'=>\$data->id))",
            'imageUrl'=>'/path/to/copy.gif',  // image URL of the button. If not set or false, a text link is used
            'options' => array('class'=>'copy'), // HTML options for the button
        ),
    ),
),
Run Code Online (Sandbox Code Playgroud)

在此示例中,有三个默认按钮和一个自定义"复制"按钮.如果您不想要某些默认按钮(即查看,更新和删除),则可以将其删除.然后,定义您添加的按钮的属性.我定义了标签,网址,图片和HTML选项.