Yii2:自定义LoginForm不起作用

时间:2016-08-08 20:32:14

标签: php yii2

我正在编写自己的登录表单以验证用户的尝试。 这是我的代码。

LoginForm.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;

    private $user;

    public function rules(){
        return [
            [['username','password'],'trim'], 
            [['username','password'],'required','message'=>'Nothing Input Yet'],
            ['username','validateUsername'],
            ['rememberMe', 'boolean'],
            ];
    }

    public function validateUsername($attribute, $params){
        $user = User::find()->where(['username'=>$this->$attribute])->asArray()->one();
        if(!$user || md5($this->password)!=$user['password']){
                $this->addError($attribute,'Username/Password Error');
            }else{
                $this->user = $user;
            }
    } 
}

索引代码:

<div class="container">
<?=Html::beginForm('','post',['enctype'=>'multipart/form-data','class'=>'form-signin'])?>

        <h2 class="form-signin-heading">Please sign in</h2>
        <?=Html::label('Username','username',['class'=>'sr-only'])?>
        <?=Html::input('text','username',$model->username,['id'=>'username','class'=>'form-control','placeholder'=>'Username','autofocus'=>true])?>
        <?=Html::error($model,'username',['class'=>'error'])?>
        <?=Html::label('Password','password',['class'=>'sr-only'])?>
        <?=Html::input('password','password',$model->password,['id'=>'inputPassword','class'=>'form-control','placeholder'=>'Password'])?>
        <?=Html::error($model,'password',['class'=>'error'])?>
        <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>

这是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{
            echo "bad";
        }

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

}

现在我的问题是,无论我输入什么或留空,我提交表格后都没有回应。只显示&#34;坏&#34;输出。 我检查了所有代码,无法找出错误的地方。甚至来自LoginForm模型的错误消息。例如:&#39;没有任何输入&#39;。

ps:我发现可能有一种称为退出的方式,但尚未尝试过,想先修改我自己的代码,然后再使用下一个内置方法。

附上结果输出图片。 enter image description here

2 个答案:

答案 0 :(得分:1)

Yii2在用户组件中有一个内置方法,用于创建名为login的用户会话。您可以Yii::$app->user->login($user)访问该功能。

这是一个添加了额外方法的课程。

// may be doing it after validating
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;

 private $user;

 public function rules(){
    return [
        [['username','password'],'trim'], 
        [['username','password'],'required','message'=>'Nothing Input Yet'],
        ['username','validateUsername'],
        ['rememberMe', 'boolean'],
        ];
 }

 public function validateUsername($attribute, $params){
    $user = User::find()->where(['username'=>$this->$attribute])->asArray()->one();
    if(!$user || md5($this->password)!=$user['password']){
            $this->addError($attribute,'Username/Password Error');
        }else{
            $this->user = $user;
        }
 } 
}

// adding this below method
public function login(){
 if($this->user && Yii::$app->user->login($this->user)) return true;
 return false;

}

在控制器中调用该新方法。

if($model->load(Yii::$app->request->post()) && $model->validate() && $model->login()){
        return $this->redirect(['site/index']);
}

注意不要忘记在配置中的User组件中添加user类。

答案 1 :(得分:0)

检查$model->validate() 可能是您在验证规则方面存在一些问题

  $model->load(\Yii::$app->request->post());

  if ($model->validate()) {
     var_dump('validation ok');

  } else {
      // validation failed: $errors is an array containing error messages
      $errors = $model->errors;
  }

尝试添加安全验证

public function rules(){
    return [
        [['username','password'],'trim'], 
        [['username','password'],'required','message'=>'Nothing Input Yet'],
        ['username','validateUsername'],
        ['rememberMe', 'boolean'],
        [['verification'], 'safe'],
        ];
}