yii : 如何 ajax 更新 cgridview [英] yii : how to ajax update the cgridview

查看:18
本文介绍了yii : 如何 ajax 更新 cgridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:如何通过ajax更新CgridVeiw?

状态:我已经完成了 cookie.但是有一个问题.当页面上传时,日期总是显示在起始日期和截止日期文本框中.并且当重新加载页面时,它不会清除.

这是我的看法

<?php $form=$this->beginWidget('CActiveForm', array('id'=>'页面表单','enableAjaxValidation'=>true,));?><div style="margin-top:30px;"><b>来自:</b><?php$this->widget('zii.widgets.jui.CJuiDatePicker', array('name'=>'from_date',//帖子参数名称//'value'=>Yii::app()->request->cookies['from_date']->value,//提交后的值来自cookie'选项'=>数组('showAnim'='折叠','dateFormat'=''yy-mm-dd',),'htmlOptions'=>数组('样式'=>'高度:20px;'),));?><span>&nbsp;&nbsp;&nbsp;</span><b>至:</b><?php$this->widget('zii.widgets.jui.CJuiDatePicker', array('name'='to_date',//'value'=>Yii::app()->request->cookies['to_date']->value,'选项'=>数组('showAnim'='折叠','dateFormat'=''yy-mm-dd',),'htmlOptions'=>数组('样式'=>'高度:20px;'),));?><span>&nbsp;&nbsp;&nbsp;</span><?php echo CHtml::submitButton('Go');?><?phpecho CHtml::ajaxSubmitButton('Search', CHtml::normalizeUrl(array('index')),大批('成功'=>'js:'.'功能(){'.'$.fn.yiiGridView.update("acc-payment-recei-grid", {u​​rl:"index"});'.'}',),数组('id'=>'go', 'name'=>'go'));?><?php $this->endWidget();?><p style="float:right;"><a href="<?php echo "create"; ?>"class="btn btn-info">新的付款接收</a></p>

<风格>.items 表 tr:last-child td:first-child {-moz-border-radius-bottomleft:10px;-webkit-border-bottom-left-radius:10px;边框左下角半径:10px}.items 表 tr:last-child td:last-child {-moz-border-radius-bottomright:10px;-webkit-border-bottom-right-radius:10px;边框右下角半径:10px}</风格><?php $this->widget('zii.widgets.grid.CGridView', array('id'=''acc-payment-recei-grid','dataProvider'=>$accpaymentrecei->search(),//'过滤器'=>$accpaymentrecei,'列'=>数组(//'ID',数组('名称' => 'acc_category_id','value'=>'(isset($data->acccategories->name)) ?CHtml::encode($data->acccategories->name):""',),数组('名称' => 'acc_recei_id','标题'=>'收到帐户',//'value'=>'(isset($data->method)) ?CHtml::encode($data->method) :""',),大批('名称' =>'日期','value'=>'($data->date= 0) ?"" : date("d M yy",strtotime($data->date))',),数组('名称' => '方法','value'=>'(isset($data->method)) ?CHtml::encode($data->method) :""',),数组('名称' => '说明',//'value'=>'(isset($data->method)) ?CHtml::encode($data->method) :""',),/*'创建日期','更新日期','文件名',*/大批('class'=''CButtonColumn',),),));

这是控制器

公共函数actionIndex(){$accpaymentrecei=new AccPaymentRecei('search');$accpaymentrecei->unsetAttributes();//清除所有默认值if(isset($_GET['AccPaymentRecei']))$accpaymentrecei->attributes=$_GET['AccPaymentRecei'];$acccategory = AccCategory::model()->findAll();$arr_method = array('Cash'=>'Cash', 'Cheque'=>'Cheque', 'Credit Card'=>'Credit Card', '银行转账'='银行转账');$this->from_to_date($accpaymentrecei);//出口();$this->render('index',array('accpaymentrecei'=>$accpaymentrecei,'acccategory'=>$acccategory,'arr_method'=>$arr_method,));}受保护的函数 from_to_date($model){unset(Yii::app()->request->cookies['from_date']);//第一个未设置日期的 cookieunset(Yii::app()->request->cookies['to_date']);//$model=new XyzModel('search');//你的模型$model->unsetAttributes();//清除所有默认值如果(!空($_POST)){Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', $_POST['from_date']);//为 from_date 定义 cookieYii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', $_POST['to_date']);$model->from_date = $_POST['from_date'];$model->to_date = $_POST['to_date'];}别的{Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', date("Y/m/d"));Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', date("Y/m/d"));}}

解决方案

下面的代码 - 只是示例,解决方案的主要原则.第一原则:我们不需要刷新页面(通过提交),我们只需要在请求后刷新CGridView.

解决方案有几个部分:

  1. 我们需要带有一些参数的表单.在您的情况下 - fromDatetoDate.你已经有了这个.但是我们不需要任何提交元素.根本!我们将使用 AJAX.

  2. 我们需要一些函数来发起 AJAX 请求.例如,此请求的事件将是参数 *from_date* 或 *to_date* 的更改.此函数也必须在请求后更新 CGridView.

  3. 我们需要控制器中的动作来处理 AJAX 请求.

让我们从第 2 部分开始.它可能是这样的:

<块引用>

Yii::app()->clientScript->registerScript('scriptId',"var ajaxUpdateTimeout;var ajaxRequest;$('**selector_for_parameters_fields**').change(function(){ajaxRequest = $(this).serialize();clearTimeout(ajaxUpdateTimeout);ajaxUpdateTimeout = setTimeout(function () {$.fn.yiiGridView.update(//这是 CGridView 的 id'acc-payment-recei-grid',{数据:ajaxRequest})},//这是延迟300);});");

将此代码置于视图中.备注:

$(this).serialize() - 关键时刻.查找更多信息

selector_for_parameters_fields - 给它们( fromDatetoDate )一些独特的选择器

我们使用一些 delay(300 毫秒)来减少来自不必要的 AJAX 请求的负载

现在 - 关于控制器中的操作

<块引用>

public function actionIndex($fromDate='', $toDate=''){$criteria = new CDbCriteria();if(!empty($fromDate))$criteria->addSearchCondition('你的关于 fromDate 的搜索条件');if(!empty($toDate))$criteria->addSearchCondition('你的关于 toDate 的搜索条件');$dataProvider=new CActiveDataProvider('YourModel',数组('标准' => $标准,));$this->render('YourView',array('dataProvider'=>$dataProvider,));}

它必须有效,但需要针对具体条件进行一些调整.

Q : How to ajax update the CgridVeiw?

Status : I've done with cookie. but there are a problem. it is when the page upload, the date are always show in from-date and to-date text box. and When reload the page, it doesn't clear out.

This is my view

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'page-form',
    'enableAjaxValidation'=>true,
)); ?>
<div style="margin-top:30px;">


    <b>From :</b>
    <?php
    $this->widget('zii.widgets.jui.CJuiDatePicker', array(
        'name'=>'from_date',  // name of post parameter
        //'value'=>Yii::app()->request->cookies['from_date']->value,  // value comes from cookie after submittion
         'options'=>array(
            'showAnim'=>'fold',
            'dateFormat'=>'yy-mm-dd',
        ),
        'htmlOptions'=>array(
            'style'=>'height:20px;'
        ),
    ));
    ?>
    <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <b>To :</b>
    <?php
    $this->widget('zii.widgets.jui.CJuiDatePicker', array(
        'name'=>'to_date',
        //'value'=>Yii::app()->request->cookies['to_date']->value,
         'options'=>array(
            'showAnim'=>'fold',
            'dateFormat'=>'yy-mm-dd',

        ),
        'htmlOptions'=>array(
            'style'=>'height:20px;'
        ),
    ));
    ?>
    <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <?php echo CHtml::submitButton('Go'); ?>
    <?php
        echo CHtml::ajaxSubmitButton('Search', CHtml::normalizeUrl(array('index')),
                array(  
                    'success'=>'js:'
                    .'function(){'
                    .'$.fn.yiiGridView.update("acc-payment-recei-grid", {url:"index"});'                    
                    .'}',
                ),
                array('id'=>'go', 'name'=>'go'));

    ?>
    <?php $this->endWidget(); ?>


    <p style="float:right;">
        <a href="<?php echo "create"; ?>" class="btn btn-info">New Payment Receive</a>
    </p>
</div>
<style>
.items table tr:last-child td:first-child {
    -moz-border-radius-bottomleft:10px;
    -webkit-border-bottom-left-radius:10px;
    border-bottom-left-radius:10px
}

.items table tr:last-child td:last-child {
    -moz-border-radius-bottomright:10px;
    -webkit-border-bottom-right-radius:10px;
    border-bottom-right-radius:10px
}

</style>
<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'acc-payment-recei-grid',
    'dataProvider'=>$accpaymentrecei->search(),
    //'filter'=>$accpaymentrecei,
    'columns'=>array(
        //'id',
        array('name' => 'acc_category_id',
               'value'=>'(isset($data->acccategories->name)) ? CHtml::encode($data->acccategories->name) :""',
        ),
        array('name' => 'acc_recei_id',
              'header'=> 'Account Received',
               //'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
        ),
        array(
            'name' => 'date',
            'value'=>'($data->date= 0) ? "" : date("d M yy",strtotime($data->date))',
        ),                
        array('name' => 'method',
               'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
        ),
        array('name' => 'description',
               //'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
        ),
        /*
        'created_date',
        'updated_date',
        'file_name',
        */
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); 

This is controller

public function actionIndex()
{
    $accpaymentrecei=new AccPaymentRecei('search');
    $accpaymentrecei->unsetAttributes();  // clear any default values

    if(isset($_GET['AccPaymentRecei']))
        $accpaymentrecei->attributes=$_GET['AccPaymentRecei'];



    $acccategory = AccCategory::model()->findAll();

    $arr_method = array('Cash'=>'Cash', 'Cheque'=>'Cheque', 'Credit Card'=>'Credit Card', 'Bank Transfer'=>'Bank Transfer');


    $this->from_to_date($accpaymentrecei);
    //exit();
    $this->render('index',array(
        'accpaymentrecei'=>$accpaymentrecei,
        'acccategory'=>$acccategory,
        'arr_method'=>$arr_method,
    ));
}

protected function from_to_date($model)
{
    unset(Yii::app()->request->cookies['from_date']);  // first unset cookie for dates
    unset(Yii::app()->request->cookies['to_date']);

    //$model=new XyzModel('search');  // your model

    $model->unsetAttributes();  // clear any default values

    if(!empty($_POST))
    {
        Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', $_POST['from_date']);  // define cookie for from_date
        Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', $_POST['to_date']);
        $model->from_date = $_POST['from_date'];
        $model->to_date = $_POST['to_date'];
    }else{
        Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', date("Y/m/d"));
        Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', date("Y/m/d"));    
    }
}

解决方案

Code below - it's only example, main principles of solution. First principle: we don't need refresh page (by the submit), we need only refresh CGridView after request.

The solution has a few parts:

  1. We need form with some parameters. In your case - fromDate and toDate. You have this one already. But we don't need any submit element. At all! We will use AJAX.

  2. We need some function for initiate AJAX-request. For example, let's event for this request will be change of parameters *from_date* or *to_date*. This function also must update CGridView after request.

  3. We need action in controller for processing AJAX-request.

Let's begin from part 2. It may be some like this:

Yii::app()->clientScript->registerScript('scriptId',
    "var ajaxUpdateTimeout;
    var ajaxRequest;
    $('**selector_for_parameters_fields**').change(function(){  
        ajaxRequest = $(this).serialize();
        clearTimeout(ajaxUpdateTimeout);
        ajaxUpdateTimeout = setTimeout(function () {
            $.fn.yiiGridView.update(
// this is the id of the CGridView
                'acc-payment-recei-grid',
                {data: ajaxRequest}
            )
        },
// this is the delay
        300);
    });"
);

Place this code into view. Notes:

$(this).serialize() - key moment. Look for more info

selector_for_parameters_fields - give them ( fromDate and toDate ) some unique selector

We use some delay (300 ms) for decreasing loading from unnecessary AJAX-requests

Now - about action in Controller

public function actionIndex($fromDate='', $toDate='')       
{
  $criteria = new CDbCriteria();   
  if(!empty($fromDate))
    $criteria->addSearchCondition('your search condition about fromDate');    
  if(!empty($toDate))
    $criteria->addSearchCondition('your search condition about toDate');                 
   $dataProvider=new CActiveDataProvider('YourModel',
        array('criteria' => $criteria,));           
   $this->render('YourView',array('dataProvider'=>$dataProvider,)); 
 }

It must works, but requires some tuning for concrete conditions.

这篇关于yii : 如何 ajax 更新 cgridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆