yii : how to ajax update the cgridview

2020-07-27 02:27发布

问题:

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"));    
    }
}

回答1:

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.



标签: php gridview yii