我能够在不依赖 javascript 的情况下完成这项工作。步骤如下:
将表单添加到您的视图文件
这将允许将作为 html 输入元素的复选框值发布到您的控制器。
<?php echo CHtml::beginForm(); ?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'selectableRows' => 2,
'columns' => array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn'
),
'id',
'username',
'content',
array(
'name' => 'created',
'value' => '$data->created'
),
),
));
?>
<div>
<?php echo CHtml::submitButton('Approve', array('name' => 'ApproveButton')); ?>
<?php echo CHtml::submitButton('Delete',
array('name' => 'DeleteButton',
'confirm' => 'Are you sure you want to permanently delete these comments?'));
?>
</div>
<?php echo CHtml::endForm(); ?>
请注意,通过将“名称”选项传递给 submitButton,它可以知道在控制器中单击了哪个按钮。
给你的复选框列一个 id
以前我有:
'columns' => array(
array(
'class' => 'CCheckBoxColumn'
),
我把它改成了:
'columns' => array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn'
),
现在您可以通过$_POST['selectedIds'] 将所选行作为数组引用。默认情况下,CCheckBoxColumn 将使用网格视图中模型项的主键(但您可以更改此设置),因此 selectedIds 将是所选主键的数组。
修改控制器以处理选定的行
public function actionApprove()
{
if (isset($_POST['ApproveButton']))
{
if (isset($_POST['selectedIds']))
{
foreach ($_POST['selectedIds'] as $id)
{
$comment = $this->loadModel($id);
$comment->is_published = 1;
$comment->update(array('is_published'));
}
}
}
// similar code for delete button goes here
$criteria = new CDbCriteria();
$criteria->condition = 'is_published = 0';
$criteria->order = 'created DESC';
$dataProvider = new CActiveDataProvider('Comment');
$dataProvider->criteria = $criteria;
$this->render('approve', array(
'dataProvider' => $dataProvider,
));
}
我使用这篇 Yii wiki 文章帮助我想出了这个解决方案:Working with CGridView in Admin Panel
不确定这是否是理想的方法,但它确实有效。我愿意接受改进建议或其他方法。