yii2bootstrap-modalyii2-advanced-appyii2-basic-app

Yii2 render view as modal, Pop up Window for forms


Render view page as a modal for preview:

<h1><?= Html::encode($this->title) ?></h1>

<p>
    <?= Html::button('Create Branches', ['value'=>Url::to(['/branches/create']),'class' => 'btn btn-success','id'=> 'modalButton']) ?>
</p>

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

    echo "<div id='modalContent'></div>";
    Modal::end();
?>

My controller:

public function actionCreate()
{
    return $this->renderAjax('create', [
                'model' => $model,
            ]);
}

My script:

$(function () {
$('#modalButton').click(function () {
    $('#modal').modal('show')
        .find('#modalContent')
        .load($(this).attr('value'));
    });
});

But when I click the link it open a viewpage with no CSS, not a pop-up modal. Please help me with this. Thank you


Solution

  • You can update your code as this.

    <h1><?= Html::encode($this->title) ?></h1>
    
    <p>
    <!-- updated id to class here -->
      <a class="modalButton btn btn-success" href="<?=Url::to(['/branches/create']) ?>">
    </p>
    
    <?php
        Modal::begin([
            'header'=>'<h4>Branches</h4>',
            'id'=>'modal',
            'size'=>'modal-lg',
        ]);
    
        echo "<div id='modalContent'></div>";
        Modal::end();
    ?>
    

    Update Jquery event.

    $(function(){
        // changed id to class
        $('.modalButton').on('click', function (){
            $.get($(this).attr('href'), function(data) {
              $('#modal').modal('show').find('#modalContent').html(data)
           });
           return false;
        });
    });