Yii CGridView button - call parametrized javascript function

Joe picture Joe · Mar 25, 2013 · Viewed 7.8k times · Source

I need to create a CGridView with one button and make the button call javascript function like this:

$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'projectCities',
    'summaryText' => '',
    'dataProvider' => $model->getCitiesProvider(),
    'columns' => array(
        'name',
        'directional',
        'customCount',
        array(
            'class'=>'CButtonColumn',
            'template'=>'{delete}',
            'buttons' => array(
                'delete' => array(
                    'url' => '',
                    'click' => '',
                    'options' => array(
                        'onclick' => 'removeCity(this, $data->idCity, 
                                      $model->idProject); return false;',
                    ),                          
                )
            ),
        )
    ),
    ));

Ofcourse it's not working, because the generated html is:

<a class="delete" title="Delete" onclick="removeCity(this, $data->idCity, $model->idProject); return false;">

Is there a way to do it so there will be proper id in the javascript function call?

Answer

cetver picture cetver · Mar 25, 2013
//Controller:
public function gridButtons($model)
{   
    return array(
        'class'=>'CButtonColumn',
        'template'=>'{delete}',
        'buttons' => array(
            'delete' => array(
                'url' => '',
                'click' => '',
                'options' => array(
                    'onclick' => sprintf(
                        'js:removeCity(this, %d, %d);return false;',
                        $model->idCity, $model->idProject
                    ),
                ),                          
            )
        ),
    )
}
//view
$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'projectCities',
    'summaryText' => '',
    'dataProvider' => $model->getCitiesProvider(),
    'columns' => array(
        'name',
        'directional',
        'customCount',
        array(            
            'value' => array($this, 'gridButtons'),            
        ),        
    ),
));