我想创建自己的登录方法,但首先我可以尝试使用验证然后重定向到页面;但是,validate()方法不起作用。 这是我的代码。 的LoginController:
<?php
namespace backend\controllers;
use yii\web\Controller;
use common\models\LoginForm;
use Yii;
class LoginController extends Controller{
public $layout = 'login' ;
public function actionIndex(){
$model = new LoginForm();
if($model->load(Yii::$app->request->post() && $model->validate())){
return $this->redirect(['site/index']);
}else{
var_dump(Yii::$app->request->isPost);
echo "<br>";
var_dump($model->load(Yii::$app->request->post()));
echo "To be continued...";
}
return $this->render('index',['model' => $model]);
}
}
这是LoginForm.php:
<?php
namespace common\models;
use Yii;
use yii\base\Model;
use common\models\User;
class LoginForm extends Model{
public $username;
public $password;
public $rememberMe = true;
public $verification;
public function rules(){
return [
[['username','password'],'required','message'=>'{attribute}Write Something...'],
['username','validateUser'],
//['password', 'validatePassword'],
];
}
/*Continue later after redirect works
public function validateUser($attribute,$params){
$user = User::findOne(['username'=>$this->$attribute]);
if(!$user || (md5($this->password) != $user['password'])){
$this->addError($this->attribute,'Errors Here...');
}
}
*/
这是我的登录名/ index.php
<?php
use yii\helpers\Html;
use Yii;
//http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html
$this->registerCssFile('@web/css/bslogin.css');
?>
<div class="container">
<?=Html::beginForm('','post',['class'=>'form-signin'])?>
<h2 class="form-signin-heading">Please sign in</h2>
<?=Html::activeInput('text',$model,'username',['id'=>'username','class'=>'form-control','placeholder'=>'Username','autofocus'=>true])?>
<?=Html::error($model,'username')?>
<?=Html::activeInput('password', $model,'password',['id'=>'inputPassword','class'=>'form-control','placeholder'=>'Password'])?>
<?=Html::error($model,'password')?>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<?=Html::submitButton('Login',['class'=>'btn btn-lg btn-primary btn-block'])?>
<?=Html::endForm()?>
</div>
因此,问题是:
不确定我哪里做错了,任何帮助都会受到赞赏。
答案 0 :(得分:0)
看起来你在这里只是语法错误:
if($model->load(Yii::$app->request->post() && $model->validate())){
将其更改为
if($model->load(Yii::$app->request->post()) && $model->validate()){