How to implement Yii2 Modal Dialog on Gridview view and update button?

为君一笑 提交于 2020-01-09 03:50:48

问题


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(); ?>

回答1:


First of all you should add the class to the view link, not id, since there are more than one element:

Change in options:

'class' => 'activity-view-link',

And in JS:

$('.activity-view-link').click(function() {

You can extract element id from corresponding parent tr. It's stored in data-key attribute.

$('.activity-view-link').click(function() {
    var elementId = $(this).closest('tr').data('key');
}

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:

public function actionView($id)
{
    $model = YourModel::findOne($id);
    if (!$model) {
        // Handle the case when model with given id does not exist
    }

    return $this->renderAjax('view', ['id' => $model->id];
}

Example of AJAX call:

$(".activity-view-link").click(function() {
    $.get(
        .../view // Add missing part of link here        
        {
            id: $(this).closest('tr').data('key')
        },
        function (data) {
            $('.modal-body').html(data);
            $('#activity-modal').modal();
        }  
    );
});



回答2:


Here is how I approached this. First I created the button in the grid view as follows:

[
    'class' => 'yii\grid\ActionColumn',
    'options'=>['class'=>'action-column'],
    'template'=>'{update} {delete}',
    'buttons'=>[
        'update' => function($url,$model,$key){
            $btn = Html::button("<span class='glyphicon glyphicon-pencil'></span>",[
                'value'=>Yii::$app->urlManager->createUrl('example/update?id='.$key), //<---- here is where you define the action that handles the ajax request
                'class'=>'update-modal-click grid-action',
                'data-toggle'=>'tooltip',
                'data-placement'=>'bottom',
                'title'=>'Update'
            ]);
            return $btn;
        }
    ]
],

Next add the following to your view file:

use yii\bootstrap\Modal;

and add the section which would hold your modal content

<?php
    Modal::begin([
        'header'=>'<h4>Update Model</h4>',
        'id'=>'update-modal',
        'size'=>'modal-lg'
    ]);

    echo "<div id='updateModalContent'></div>";

    Modal::end();
?>

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:

$(function () {
    $('.update-modal-click').click(function () {
        $('#update-modal')
            .modal('show')
            .find('#updateModalContent')
            .load($(this).attr('value'));
    });
});

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:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    if ($model->load(Yii::$app->request->post()) && $model->validate() ) {
        //prepare model to save if necessary
        $model->save();
        return $this->redirect(['index']); //<---This would return to the gridview once model is saved
    }
    return $this->renderAjax('update', [
        'model' => $model,
    ]);
}

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.




回答3:


i added this following code using natral scripts.

Yii::$app->urlManager->createUrl(['self-assessment-detail/update','id'=>$key])


来源:https://stackoverflow.com/questions/28358398/how-to-implement-yii2-modal-dialog-on-gridview-view-and-update-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!