php - Login Modal Yii

one text

Solution:

Try it:

frontend/controllers/SiteController.php file example with default login action:

public function actionLogin()
{
    if (!Yii::$app->user->isGuest) {
        return $this->goHome();
    }

    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->goBack();
    } else {
        $model->password = '';

        return $this->render('login', [
            'model' => $model,
        ]);
    }
}

public function actionLoginAjax()
{
    if (Yii::$app->request->isAjax) {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->renderAjax('_form_login', [
                'model' => $model,
            ]);
        }
    }

    return $this->redirect(['login']);
}

frontend/views/login.php file example:

<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;

$this->title                   = 'Contact';
$this->params['breadcrumbs'][] = $this->title;

\yii\bootstrap\Modal::begin([
                                'id'     => 'modal-login',
                                'header' => '<h5 class="modal-title">Login</h5>',
                                'size'   => \yii\bootstrap\Modal::SIZE_LARGE,
                            ]);
\yii\bootstrap\Modal::end();
$js = <<<JS
$(function() {
   $('.send-login').click(function(e) {
     e.preventDefault();
     $('#modal-login').modal('show').find('.modal-body').load($(this).attr('href'));
   });
});
JS;
$this->registerJs($js);
?>
<div class="site-login">
    <h1><?= Html::encode($this->title) ?></h1>

    <?= Html::a('Login', [
        'site/login-ajax',
    ], ['class' => ' btn btn-success send-login']); ?>

    <p>Please fill out the following fields to login:</p>

    <div class="row">
        <div class="col-lg-5">
            <?php $form = ActiveForm::begin(['id' => 'login-form']); ?>

                <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>

                <?= $form->field($model, 'password')->passwordInput() ?>

                <?= $form->field($model, 'rememberMe')->checkbox() ?>

                <div style="color:#999;margin:1em 0">
                    If you forgot your password you can <?= Html::a('reset it', ['site/request-password-reset']) ?>.
                    <br>
                    Need new verification email? <?= Html::a('Resend', ['site/resend-verification-email']) ?>
                </div>

                <div class="form-group">
                    <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
                </div>

            <?php ActiveForm::end(); ?>
        </div>
    </div>
</div>

_form_login.php file in the same directory login.php and example below.

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

/**
 * @var $this  \yii\web\View
 */
$js = <<<JS
$("document").ready(function(){
    //this will work with mulitpart data or regular form
    $('#login-form').submit(function(e) {
        e.preventDefault();
        var form = document.getElementById('login-form');
        $.ajax({
              url: $(this).attr('action'),
              type: $(this).attr('method'),
              data: new FormData(form),
              mimeType: 'multipart/form-data',
              contentType: false,
              cache: false,
              processData: false,
              dataType: 'json',
              success: function(data) {
                  //if there are serverside errors then ajax show them on the page
                  if (data.errors) {
                      $.each(data.errors, function(key, val) {
                          var el = $('#' + key);
                          el.parent('.form-group').addClass('has-error');
                          el.next('.help-block').html(val);
                      });
                  } else {
                      //reload pjax and close boostrap modal
                      //$('#modal').modal('hide');
                  }
              }
        });
    });
});
JS;
$this->registerJs($js);
?>
<?php Pjax::begin(['id' => 'pjax-create', 'enablePushState' => false]) ?>
<?php $form = ActiveForm::begin(['id' => 'login-form', 'options' => ['data-pjax' => true]]); ?>

<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>

<?= $form->field($model, 'password')->passwordInput() ?>

<?= $form->field($model, 'rememberMe')->checkbox() ?>

    <div class="form-group">
        <?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
    </div>

<?php ActiveForm::end(); ?>
<?php Pjax::end() ?>

frontend/models/LoginForm.php file without any changes:

<?php
namespace common\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        }
        
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}

Source