GEOFFREY MWANGI GEOFFREY MWANGI - 2 months ago 6
Ajax Question

Calling a function on grid action coumn click

I have a grid in yii that has an action column with a custom button I would like to call function when the grid button is clicked but i get an error

This is my code:

[
'class' => 'kartik\grid\ActionColumn',
'template' => '{approve}{new}{reject}',
'buttons' => [
'approve' => function ($url, $model) {
return Html::button('<i class="fa fa-check"></i>', ['value' => Url::to('approvetruck?id='.$model->id),'style' =>'background:none;border:none;','id' => 'approve','onclick'=>'alert('.$model->id.')']);
},
'reject' => function ($url, $model) {
return Html::button('<i class="fa fa-close"></i>', ['value' => Url::to('checktruck?id='.$model->id."&category=1"),'style' =>'background:none;border:none;', 'onclick'=>'reject('.$model->id.')');
},

],
'dropdown' => false,
'vAlign' => 'middle',
'urlCreator' => function ($action, $model, $key, $index) {
return '#';
},


'deleteOptions' => ['label' => '<i class="glyphicon glyphicon-remove"></i>']
]


After the grid i have(on the same page)

<?php
$script = <<< JS
function reject(id) {
alert(id);

}

JS;
$this->registerJs($script);
?>


The first one approve doing the alert works but the reject which calls a function reject fails..
it returns an error of
Uncaught ReferenceError: reject is not defined


How do i do this

Answer

It seems you have to use below code for register js

<?php 

$this->registerJs(' 
    function reject(id) {
    alert(id);
    }', \yii\web\VIEW::POS_HEAD); 
?> 

that will add the js in head part and it may get the function which you defined