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 directorylogin.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;
}
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Yii is a simple yet high performance generic component framework based framework. It is known for its high performance, but above all, it is famous for its simplicity. This framework appeared in December 2008. It allows you to use third-party code, and its Gii code generator allows you to quickly create basic structures from which you can build your own solutions.
https://www.yiiframework.com/
Bootstrap is not exclusively a CSS framework, but its most popular features are CSS-centric. These include a powerful grid, icons, buttons, map components, navigation bars, and more.
https://getbootstrap.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.