I would like to implement Yii2 modal dialog box on my gridview when view or update button is clicked at each row.
Can anyone kindly advise on how to implement it?
With advice from arogachev: This is an update on my codes
<?php
//var_dump($dataProvider);
$gridColumns = [
[
'format' => 'html',
'attribute' => 'avatar',
'label'=>'Image',
'headerOptions' => ['width' => '80%',],
],
[ 'class' => 'yii\grid\ActionColumn',
'template' => '{view} {delete}',
'headerOptions' => ['width' => '20%', 'class' => 'activity-view-link',],
'contentOptions' => ['class' => 'padding-left-5px'],
'buttons' => [
'view' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>','#', [
'id' => 'activity-view-link',
'title' => Yii::t('yii', 'View'),
'data-toggle' => 'modal',
'data-target' => '#activity-modal',
'data-id' => $key,
'data-pjax' => '0',
]);
},
],
],
];
?>
<?php
Pjax::begin();
echo \kartik\grid\GridView::widget([
'dataProvider' => $dataProvider,
'columns'=>$gridColumns,
'summary'=>false,
'responsive'=>true,
'hover'=>true
]);
Pjax::end();
?>
<?php $this->registerJs(
"$('.activity-view-link').click(function() {
$.get(
'imgview',
{
id: $(this).closest('tr').data('key')
},
function (data) {
$('.modal-body').html(data);
$('#activity-modal').modal();
}
);
});
"
); ?>
<?php
?>
<?php Modal::begin([
'id' => 'activity-modal',
'header' => '<h4 class="modal-title">View Image</h4>',
'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">Close</a>',
]); ?>
<div class="well">
</div>
<?php Modal::end(); ?>
Here is how I approached this. First I created the button in the grid view as follows:
Next add the following to your view file:
and add the section which would hold your modal content
Now you need the javascript (jQuery in this case) to handle the click event and make the ajax call. I created a mymodal.js in the @web/scripts folder file like so:
Add this file to the view file that hosts your gridview.
registerJsFile('@web/scripts/mymodal.js',['depends' => [\yii\web\JqueryAsset::className()]]);?>All this is left is to setup the action that will handle your ajax request. In ExampleController.php (following from the setup in the gridview button above) add the following action:
After this you just need to make sure that you have your update.php view file setup with the model form and submit button and your good to go.
First of all you should add the class to the view link, not id, since there are more than one element:
Change in options:
And in JS:
You can extract element id from corresponding parent
tr
. It's stored indata-key
attribute.Note that in case of composite primary keys it will be object, not a string / number.
Once you get id, load according model with AJAX and insert content into modal body.
Example of related method in controller:
Example of AJAX call: