How to Implement modal window in yii 2 framework

The work of implementing the modal window will be made easy by Bootstrap, which is a default framework bundled with the basic app.

The modal window is composed by an almost pre-determined markup and an additional JS, which provides the interaction part, thereby hooking it to the rest of the interface. I hope that the simplicity of its implementation will let you focus on the aim that lies behind it.

The following code has deliberately been taken from the Bootstrap documentation, which can be found at http://getbootstrap.com/javascript/#modals. Since the modal window can be opened from any part of the website without going to the login page, we will have to add it to the overall layout template:

    <!-- views/layouts/main.ph -->
    </footer>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">Login</h4>
                </div>
                <div class="modal-body">
                    <?= $this->render('/site/login-modal.php', ['model' => Yii::$app->controller->loginForm]); ?>
                </div>
            </div>
        </div>
    </div>

<?php $this->endBody() ?>
<!-- ... -->

As you can see, we have moved the modal form to a separate template, which will receive the model of the form as a variable, keeping everything self-contained and organized. Please note from where the model takes its value. We’re going to discuss it while implementing the controller.

The login-modal.php template is just a rip-off of the original login.php template, which can be found in the same directory without H1 in the title and the “remember me” checkbox. We just need to add a placeholder to show the error that is coming from the API. This is done to inform and debug it.

<!-- views/site/login-modal.php
<!-- ... -->
<div class="alert alert-danger alert-dismissible fade in">
    <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
    <p class="error"></p>
</div>
<!-- ... -->

 

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares

Get the best in web dev

Join dunebook.com and recieve best in web dev , once a week FREE

An email has been Sent to your Inbox ! Please Confirm your Subscription :)