kzht91 kzht91 - 2 months ago 50
Javascript Question

Custom buttons Action Column, yii2

I want to change default buttons on ActionColumn (GridView::widget) using modal popup window. here is my code:

['class' => 'yii\grid\ActionColumn',
'contentOptions' => ['style' => 'width: 8.7%'],
'visible'=> Yii::$app->user->isGuest ? false : true,
'buttons'=>[
'view'=>function ($url, $model) {
$t = 'index.php?r=site/view&id='.$model->id;
return Html::button('<span class="glyphicon glyphicon-eye-open"></span>', ['value'=>Url::to($t), 'class' => 'btn btn-default btn-xs', 'id'=>'modalButtonView']);
},
'update'=>function ($url, $model) {
$t = 'index.php?r=site/update&id='.$model->id;
return Html::button('<span class="glyphicon glyphicon-pencil"></span>', ['value'=>Url::to($t), 'class' => 'btn btn-default btn-xs', 'id'=>'modalButtonView']);
},
],
],


Only first button works well, another buttons doesn't. What should I change? And can I use anchor tags instead buttons?
Here are my js and ModalWidget:

$(function(){
$('#modalButtonView').click(function(){
$('#modalView').modal('show').find('#modalContentView').load($(this).attr('value'));

});});


Modal::begin(['id'=>'modalView', 'size'=>'modal-md']);
echo "<div id='modalContentView'></div>";
Modal::end();

Answer

The basic rules in html.

ID must unique.

use this code

    ['class' => 'yii\grid\ActionColumn',
    'contentOptions' => ['style' => 'width: 8.7%'],
    'visible'=> Yii::$app->user->isGuest ? false : true,
    'buttons'=>[
        'view'=>function ($url, $model) {
            $t = 'index.php?r=site/view&id='.$model->id;
            return Html::button('<span class="glyphicon glyphicon-eye-open"></span>', ['value'=>Url::to($t), 'class' => 'btn btn-default btn-xs custom_button']);
        },
        'update'=>function ($url, $model) {
            $t = 'index.php?r=site/update&id='.$model->id;
            return Html::button('<span class="glyphicon glyphicon-pencil"></span>', ['value'=>Url::to($t), 'class' => 'btn btn-default btn-xs custom_button']);
        },
    ],
],

then yor jquery

$(function(){
$('.custom_button').click(function(){
    $('#modalView').modal('show').find('#modalContentView').load($(this).attr('value'));

});});

    Modal::begin(['id'=>'modalView', 'size'=>'modal-md']);
echo "<div id='modalContentView'></div>";
Modal::end();
Comments