Update a part of content using AJAX when select a GridView row

You are viewing revision #5 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#4)next (#6) »

Suppose you want to refresh a form or any content when a single row of CGridView is selected

how to achieve that ?

In your view file modify your cgridview like that

$this->widget('zii.widgets.grid.CGridView', array(
        'id' => 'my-items-grid',
        'dataProvider' => $model->search(),
        'selectableRows' => 1, //permit to select only one row by the time
        'selectionChanged' => 'updateABlock', //javascript function that will be called
        'filter' => $model,
        'columns' => array(
            'id',
             ...
             ...

Into the same view just add this (or using javascript register)

<script type="text/javascript">
    function updateABlock(grid_id) {

        var keyId = $.fn.yiiGridView.getSelection(grid_id);
        keyId  = keyId[0]; //above function returns an array with single item, so get the value of the first item
    
        $.ajax({
            url: '<?php echo $this->createUrl('PartUpdate'); ?>',
            data: {id: keyId},
            type: 'GET',
            success: function(data) {
                $('#part-block').html(data);
            }
        });
    }
</script>

In your controller add the appropriate action method

public function actionPartUpdate($id = null) {
        $model = MyModel::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');

        $this->renderPartial('_myModelview', array('model' => $model));
        Yii::app()->end();
}

view file _myModelview.php could be contains any code including $model data. Remember to includes you code between this

<div id='part-block'>
//your php-html code
</div>