Question

I'm having problems with CGridView and one custom Formatter that uses javascript. When CGridView triggers an ajax request of any kind, my Formatter that works with javascript stops working.

Let's try one trivial example:

The Formatter

class DFormatter extends CFormatter {

    public function formatTest(){
        $js      = <<<EOD
        console.log("test");
        EOD;

        $cs = Yii::app()->getClientScript();
        $cs->registerScript("testjs", $js);

        return false;
    }
}

The view:

<?php $this->widget('zii.widgets.grid.CGridView',
  array(
       'id'           => 'development-grid',
       'dataProvider' => $model->search(),
       'filter'       => $model,
       'columns'      => array(
         'id',
         array(
           'name'  => 'testField',
           'type'  => 'test',
         ),
         array(
           'class' => 'CButtonColumn',
         ),
       ),
  )); ?>

After the first Ajax Request, the javascript code used in the formatter stops working, How can I get my javascript code works after every ajax call made by CGridView Widget?

Thanks.

Was it helpful?

Solution

You should not put scripts in the formatter.

Remove:

    $js      = <<<EOD
    console.log("test");
    EOD;

    $cs = Yii::app()->getClientScript();
    $cs->registerScript("testjs", $js);

Configure your grid view:

<?php $this->widget('zii.widgets.grid.CGridView', array(
    //.. other options

    // ADD THIS
    'afterAjaxUpdate' => 'function() { afterAjaxUpdate(); }',

Add to <head> of /layouts/main.php:

<script src="<?= Yii::app()->getBaseUrl(true); ?>/js/myCustomJS.js"></script>

Create new JS file at /js/myCustomJS.js:

function afterAjaxUpdate() {
    // do your formatting here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top