使用CGridView进行批量更新


Batch update using CGridView

我想使用CCheckBoxColumn对CGridView中显示的一些记录执行批量更新,但它不起作用
下面是一个示例场景:

考虑表(MySQL):

CREATE TABLE IF NOT EXISTS `tb_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
)

添加一些行:

INSERT INTO `tb_test` (`id`, `description`, `active`) VALUES  
(1, 'Test #1', 0),  
(2, 'Test #2', 1),  
(3, 'Test #3', 0);

然后使用Gii生成默认的Model、Controller和CRUD,好吗?

好吧,在那之后,我在控制器中做了一些更改:

// unlock "active" and "ajaxupdate"
public function accessRules()
{
    ...
    array('allow',
        'actions'=>array('active','ajaxupdate'),
        'users'=>array('*'),
    ),
    ...
}
// ...other stuff
// action Active
public function actionActive()
{
    $model=new Test('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Test']))
    $model->attributes=$_GET['Test'];
    $this->render('active',array(
        'model'=>$model,
    ));
}
// action AjaxUpdate
public function actionAjaxUpdate()
{
    $check_column = $_POST['check_column'];
    print_r($check_column);
}

最后,这里是测试视图:

<?php 
$form=$this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>true,
)); 
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'test-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'enablePagination'=>false,
    'selectableRows'=>2,
    'columns'=>array(
        array(
            'id'=>'check_column',
            'class'=>'CCheckBoxColumn',
            'value'=>'$data->active',
            'checked'=>'$data->active',
        ),
        'id',
        'description',
        array(
            'class'=>'CButtonColumn',
        ),
    ),
));
?>
<script>
function reloadGrid(data) {
    $.fn.yiiGridView.update('test-grid');
}
</script>
<?php 
echo CHtml::ajaxSubmitButton('Update All',array('test/ajaxupdate'), array('success'=>'reloadGrid'));
$this->endWidget(); 
?>

我的目标是获取所有复选框的值,并对表执行批量更新,将ACTIVE列设置为true或false。

但是Yii框架只是向Ajax发送标记的检查。通过Firebug,我可以看到这样的结果:

Array
(
    [0] => 1
    [1] => 0
)

即使我标记了所有3条记录!

有没有办法得到所有复选框的值?

谢谢!

1st。可选择的行应该如下所示:

array(
            'class' => 'CCheckBoxColumn',
            'selectableRows' => '2',
            'id'=>'check_column',
            'value'=>'$data->active',
            'checked'=>'$data->active',
      ),

第二。你可以自己通过它们,所以ajaxButton看起来像:

<?php echo CHtml::ajaxButton(Yii::t("app","grid_update"), 'test/ajaxupdate', array(
    'type'=>'POST',
    'data'=>'js:{ids : $.fn.yiiGridView.getChecked("grid-id-here","check_columns").toString()}',
    'success' =>
        'js:function (data) {
               //do what you need here
           }',
), array(
    'id' => 'update_btn_'.rand(0,255),
    'class' => 'update_btn'
));?>

使用此方法,您将获得字符串,用逗号与所选行分隔。