Search code examples
yii2bootstrap-modalyii2-basic-app

Yii2 render view as modal


I want to render view page as a modal for preview

<div>
 <?php foreach($softs as $soft) { ?>
  <a id="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
  <?php 
    Modal::begin([
        'header' => 'Test',
        'id' => 'modal',
        'size' => 'modal-lg',
    ]);
    echo "<div id='modalContent'></div>";
    Modal::end();
    ?>
  <?php } ?>
</div>

My controller

 public function actionIndex()
    {
        $query = Documents::find();
        $softs = $query->where(['type_id' => 2])->all();
    return $this->render('index', [
            'softs' => $softs,
        ]);
    }    

public function actionView($id)
    {
        return $this->renderAjax('view', [
            'model' => $this->findModel($id),
        ]);
    }

My script

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

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 update your code as per below.

    <div>
     <?php foreach($softs as $soft) { ?>
      <!-- updated id to class here -->
      <a class="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
      <?php } ?>
    
      <!-- We don't need to print modal popup multiple times -->
      <?php 
        Modal::begin([
            'header' => 'Test',
            'id' => 'modal',
            'size' => 'modal-lg',
        ]);
        echo "<div id='modalContent'></div>";
        Modal::end();
        ?>
    
    </div>
    

    Update click event.

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