9

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(); ?>
esiaz
  • 619
  • 4
  • 10
  • 22
  • How the actual view / update pages will be open in that case? With link inside popover content? – arogachev Feb 07 '15 at 15:32
  • hi arogachev, inside gridview, when i click on the eye button, the view page will launched in a modal and when i click on the pencil button, the update page will be launched inside the modal. The actual view/update page is a url page which can be launched by itself. – esiaz Feb 08 '15 at 13:18
  • It is something like in Yii1, using CJuiDialog to edit rows in a CGridView, only that i need to implement it in Yii2 which i am unable to find any guide online. – esiaz Feb 08 '15 at 13:27
  • Hi i found some codes online which is similar to what i wanted, however i do not know how to send in the id of the selected row into the modal url so that i could load the relevant model inside that dialog box. – esiaz Feb 09 '15 at 08:34
  • I don't get it, how modals are related to popovers? Popovers are like tooltip but shown on click instead of hover. – arogachev Feb 09 '15 at 09:02
  • actually not necessary using popovers, i jus need them to display in modal dialog box – esiaz Feb 09 '15 at 09:15
  • Please be precise with your questions. You are asking about implementing this with Popover. Please edit question title and content so it's easy to understand what exactly you want to achieve. – arogachev Feb 09 '15 at 09:18
  • have made the necessary editing on my question thks – esiaz Feb 09 '15 at 09:22
  • So what is the current problem? Passing id of selected row to modal? – arogachev Feb 09 '15 at 09:28
  • yes..i do not know how to pass the id of that row into the modal dialog box so i could load the relevant model – esiaz Feb 09 '15 at 09:33
  • Hi, if i were to add to both view and update buttons, the modal seem to be in conflict. Same problem as http://stackoverflow.com/questions/12286332/twitter-bootstrap-remote-modal-shows-same-content-everytime . The solution seems to be adding $('#myModal').on('hidden', function () { $(this).removeData('modal'); }); to the jquery. May i know how do i apply it to here? – esiaz Feb 12 '15 at 05:08
  • It's hard to understand without seeing the code. And I think such conflict is topic for different question. Current problem is solved. – arogachev Feb 12 '15 at 05:17
  • Hi arogachev, as explained here http://stackoverflow.com/questions/28470166/yii2-modal-dialog-on-gridview-view-and-update-button-shows-same-content-for-both thanks! – esiaz Feb 12 '15 at 05:44

3 Answers3

14

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();
        }  
    );
});
robsch
  • 9,358
  • 9
  • 63
  • 104
arogachev
  • 33,150
  • 7
  • 114
  • 117
1

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.

natral
  • 986
  • 1
  • 18
  • 42
-1

i added this following code using natral scripts.

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