문제

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.

도움이 되었습니까?

해결책

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top