在 Yii 网格视图分页中保留复选框值


Retain Checkbox values in Yii gridview pagination

我有一个网格视图,其中包含一个复选框列,并且还使用分页。当我选中第一页中的一些复选框并导航到第二页并在第二页中选中另一个复选框时,我在第一页中选中的选项不会保留在那里。是否可以在分页期间保留复选框值?

网格视图的代码是

$widget = $this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'     => $model->search(),
    'cssFile'          => Yii::app()->baseUrl . '/media/js/admin/css/admingridview.css',
    //'filter' => $model,
    'ajaxUpdate'       => true,
    'enablePagination' => true,
    'columns'          => array(
        array(
            'name'   => 'id',
            'header' => '#',
            'value'  => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
        ),
        array(
            'class'          => 'CCheckBoxColumn',
            'selectableRows' => '2',
            'header' => 'Selected',
        ),
        array(
            'name'   => 'fb_user_id',
            'header' => 'FaceBook Id',
            'value'  => 'CHtml::encode($data->fb_user_id)',
        ),
        array(
            'name'   => 'first_name',
            'header' => 'Name',
            'value'  => 'CHtml::encode($data->first_name)',
        ),
        array(
            'name'   => 'email_id',
            'header' => 'Email',
            'value'  => 'CHtml::encode($data->email_id)',
        ),
        array(
            'name'   => 'demo',
            'type'   => 'raw',
            'header' => "Select",
            'value'  => 'CHtml::checkBox("email[]","",array("class"=>"check","value"=>$data->email_id))',
        ),
    ),
));

编辑:

用于记住网格视图中所选选项的扩展,检查此链接 Selgridview

感谢 bool.dev

您可以使用会话/cookie 来存储选中的值。我不太确定如何使 cookie 工作,所以我会告诉你如何使用会话来做到这一点。特别是 yii 创建的用户会话。

现在要使用会话,我们需要将选中(和未选中)的 id 传递给控制器,因此我们将修改每次 ajax 更新时发送到控制器的数据(即分页之间),为此我们利用 CGridView 的beforeAjaxUpdate选项。

我也在您的代码中使用 CCheckBoxColumn 而不是以下内容(当然,您可以修改解决方案以满足您自己的需求):

array(
     'name' => 'demo',
     'type'=>'raw',
     'header' => "Select",
     'value' => 'CHtml::checkBox("email[]","",array("class"=>"check","value"=>$data->email_id))',
),

网格视图更改:

<?php $this->widget('zii.widgets.grid.CGridView', array(
    // added id of grid-view for use with $.fn.yiiGridView.getChecked(containerID,columnID)
    'id'=>'first-grid',
    'dataProvider'=>$model->search(),
    'cssFile' => Yii::app()->baseUrl . '/media/js/admin/css/admingridview.css',
    // added this piece of code
    'beforeAjaxUpdate'=>'function(id,options){options.data={checkedIds:$.fn.yiiGridView.getChecked("first-grid","someChecks").toString(),
        uncheckedIds:getUncheckeds()};
        return true;}',
    'ajaxUpdate'=>true,
    'enablePagination' => true,
    'columns' => array(
            array(
                 'name' => 'id',
                 'header' => '#',
                 'value' => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
            ),
            array(
                 'name' => 'fb_user_id',
                 'header' => 'FaceBook Id',
                 'value' => 'CHtml::encode($data->fb_user_id)',
            ),
            array(
                 'name' => 'first_name',
                 'header' => 'Name',
                 'value' => 'CHtml::encode($data->first_name)',
            ),
            array(
                 'name' => 'email_id',
                 'header' => 'Email',
                 'value' => 'CHtml::encode($data->email_id)',
            ),
            /* replaced the following with CCheckBoxColumn
              array(
                 'name' => 'demo',
                 'type'=>'raw',
                 'header' => "Select",
                 'value' =>'CHtml::checkBox("email[]","",array("class"=>"check","value"=>$data->email_id))',
              ),
            */
            array(
                 'class' => 'CCheckBoxColumn',
                 'selectableRows' => '2',
                 'header'=>'Selected',
                 'id'=>'someChecks', // need this id for use with $.fn.yiiGridView.getChecked(containerID,columnID)
                 'checked'=>'Yii::app()->user->getState($data->email_id)', // we are using the user session variable to store the checked row values, also considering here that email_ids are unique for your app, it would be best to use any field that is unique in the table
            ),
    ),
));
?>

特别注意 beforeAjaxUpdate 和 CCheckBoxColumn 的代码,在 AjaxUpdate 之前,我们将checkedIds作为已检查的所有 id(在本例中为 email_ids)的 csv 字符串传递,并uncheckedIds为所有未选中 id 的 csv 字符串,我们通过调用函数getUncheckeds()来获取未选中的框, 紧随其后的是。请注意,当我测试时,我使用了(我的表的)整数 id 字段作为唯一字段,而不是电子邮件字段。

getUncheckeds()函数可以在 gridview 的视图文件中的任何位置注册:

Yii::app()->clientScript->registerScript('getUnchecked', "
       function getUncheckeds(){
            var unch = [];
            /*corrected typo: $('[name^=someChec]') => $('[name^=someChecks]') */
            $('[name^=someChecks]').not(':checked,[name$=all]').each(function(){unch.push($(this).val());});
            return unch.toString();
       }
       "
);

在上述函数中,请注意选择器和eachpush功能。

完成此操作后,我们需要修改此视图的控制器/操作。

public function actionShowGrid(){
     // some code already existing
     // additional code follows
     if(isset($_GET['checkedIds'])){
          $chkArray=explode(",", $_GET['checkedIds']);
          foreach ($chkArray as $arow){
               Yii::app()->user->setState($arow,1);
          }
     }
     if(isset($_GET['uncheckedIds'])){
          $unchkArray=explode(",", $_GET['uncheckedIds']);
          foreach ($unchkArray as $arownon){
               Yii::app()->user->setState($arownon,0);
          }
     }
     // rest of the code namely render()
}

就是这样,它现在应该可以工作了。

为了开发该方案,您需要知道导航时会发生什么。

当您导航到分页页面时,会进行 ajax 调用并接收新数据,并从 CActive Record 或任何数据源中获取这些数据。新数据符合数据库记录或源记录。当您再次返回上一页时,将进行 Ajax 调用并更新内容,以便与数据库中相同。

我觉得您应该暂时保存检查项目的数据,并在采取行动时将其永久保存。

你可以做这样的事情

<script type="text/javascript">
$("input:checkbox").click(function () {
    var thisCheck = $(this);
    if (thisCheck.is (':checked')){
        // do what you want here, the way to access the text is using the
        // $(this) selector. The following code would output pop up message with
        // the selected checkbox text
        $(this).val());
    }
});
</script>

您可以将临时存储保存在某个地方

还要在普通表单上完成这项工作 提交:

我想添加这个作为对bool.dev答案的评论,但我没有足够的声誉来做到这一点。所以我不得不把它放在一个单独的答案中。

bool.dev,你的回答很棒,效果很好,谢谢。

但是,正如预期的那样,它仅在 ajax 调用更新网格视图时才有效。我有网格视图构成表单的一部分,所以我希望它也适用于表单的正常提交,否则当表单上存在其他验证错误时,复选框不会再次加载。

因此,除了您所做的之外,我还在表单上添加了隐藏字段,例如:

<input type="hidden" name='checkedBox1' id='checkedBox1' value=''>
<input type="hidden" name='uncheckedBox1' id='uncheckedBox1' value=''>

然后,在提交表单之前,我的sumbit按钮运行getChecked()和getUncheckeds()函数,并将其结果存储在隐藏字段中:

if ($('#checkedBox1').length >0)   {$('[name=checkedBox1]').val(getChecked());}
if ($('#uncheckedBox1').length >0) {$('[name=uncheckedBox1]').val(getUncheckeds());}

在控制器中,除了检查 $_GET['checkedIds'] 之外,您还可以检查 $_POST['checkedBox1'] 并将其值存储到会话中,就像使用相同的会话变量为 $_GET['checkedIds'] 一样。

对 $_POST['uncheckedBox1'] 执行相同的操作。

这应该行得通。