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

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

Leave a Comment