I try to make custom login form in Yii2 Basic , without the ActiveForm widget . I made form which I want to use for login but , when I try to login it doesnt login only refresh the page without nothihng, so maybe I miss something or dont do like it should be . I use email address instead of username , and with ActiveForm it all work but when I try to make it custom there is some issue .
This is my login form that I want to make custom :
<div class="login-message">
<h1><?= Html::encode($this->title) ?></h1>
</div>
<form method="post">
<div>
<span class=""> Email </span>
<input value="<?php $model->email ?>" placeholder="Write your email address" type="text">
</div>
<div>
<span class=""> Password </span>
<input value="<?php $model->password ?>" placeholder="Write your password" type="password">
</div>
<div class="form-group">
<div>
<div class="register">
<?= Html::a(Yii::t("app", "Register"), ["/site/register"]) ?>
</div>
<br>
<div class="forgot-pas">
<?= Html::a(Yii::t("app", "Forgotten password") . "?", ["/site/forgot"]) ?>
<br>
</div>
<br>
<div class="login-button">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
</div>
<input type="hidden" value="" name="_csrf" >
</form>
My action in SiteController for Login :
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();
}
return $this->render('login', [
'model' => $model,
]);
}
Your problem is that you are missing the name
of every input. Because of this, when you try to load the post params using $model->load()
will fail.
Usually ActiveForm
generates these names in your inputs, however because you don't want to use it, you will have to generate them yourself:
<div class="login-message">
<h1><?= Html::encode($this->title) ?></h1>
</div>
<form method="post">
<div>
<span class=""> Email </span>
<input name="LoginForm[email]" value="<?php $model->email ?>" placeholder="Write your email address" type="text">
</div>
<div>
<span class=""> Password </span>
<input name="LoginForm[password]" value="<?php $model->password ?>" placeholder="Write your password" type="password">
</div>
<div class="form-group">
<div>
<div class="register">
<?= Html::a(Yii::t("app", "Register"), ["/site/register"]) ?>
</div>
<br>
<div class="forgot-pas">
<?= Html::a(Yii::t("app", "Forgotten password") . "?", ["/site/forgot"]) ?>
<br>
</div>
<br>
<div class="login-button">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
</div>
<input type="hidden" value="" name="_csrf" >
</form>
This way of naming your inputs follows the same way ActiveForm does it, because the load()
method from your model is implemented to (by default) load attributes like A[b]
where A is the model classname and b is the attribute name.