anon97
anon97

Reputation: 15

Yii2: Display modal from a clickable row in Gridview

I want to display modal after clicking a row in Gridview but the modal content won't display.

What's missing or something wrong with my code?

In main.php:

    <?php
    Modal::begin([
        'header'=>'<h4>Update '. $this->title .'</h4>',
        'id'=>'update-modal',
        'size'=>'modal-md'
    ]);

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

Modal::end();
?>

In index.php:

    <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'attribute'=>'name',
            'format'=>'raw',
            'value'=>function ($model) {
                    return Html::a($model->name, ['/unit/unit/update', 'id'=>$model->id], ['class' => 'update-modal-link',
                                                'data-toggle'=>"modal",
                                                'data-target'=>"#update-modal",
                                            ]);
             }
        ],
    ],
]); ?>

In main.js:

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

Upvotes: 1

Views: 1075

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23748

You should either use javascript or the default data-toggle and data-target attributes, you are trying to load it via 2 sources and i suspect that the problem you are facing is that it loads the modal and disappears instantly.

If that is correct remove the attributes from the anchor link in your GridView column and update it to the below.

[
    'attribute' => 'name',
    'format' => 'raw',
    'value' => function ($model) {
        return Html::a($model->name, ['/unit/unit/update', 'id' => $model->id], ['class' => 'update-modal-link']);
    }
],

Then you are trying to assignthe value attribute for the anchor which is not valid you need to target the href attribute for the anchor to get the relative url and load the modal content.

Change your javascript code to below

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

Hope this helps.

Upvotes: 1

Related Questions