Yii2 验证码详细教程,解决不显示不刷新问题

来源:互联网 发布:淘宝直播卖家怎么申请 编辑:程序博客网 时间:2024/06/05 11:42

1. 前台页面:index.php
NOTE'captchaAction'=>'/test/login/captcha',//【test为模块,login为控制器,需要指定,用默认控制器site无需指定】

如果你是直接在yii2默认控制器SiteController.php渲染的视图,那么上图中captchaAction参数可以不用设置。如果不是,那就必须要指定清楚,因为captchaAction默认site/captcha。(这个是导致一些朋友验证码出不来的原因)。 


<?phpuse yii\widgets\ActiveForm;use yii\helpers\Html;use yii\captcha\Captcha;?><?php $form = ActiveForm::begin([    'id' => 'login-form',]) ?><?= $form->field($model, 'username')->textInput(array('id' => 'xxx')) ?><?= $form->field($model, 'password')->passwordInput(); ?><?= $form->field($model, 'rememberMe')->checkbox(); ?><?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',    'captchaAction'=>'/test/login/captcha',//【test为模块,login为控制器,需要指定,用默认控制器sit无需指定】]) ?><?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']); ?><?php ActiveForm::end() ?>

2. 控制器:LoginController

NOTE::

1 .  

如果你的yii程序启用了权限控制,还需要设置
behaviors的rules;允许验证码对应的action在没有登录的情况下也能被访问(这个是导致一些朋友验证码出不来的原因
2. actions 增加captha

3. rules增加2项目返回值

        4. 加载视图用render,否则不能加载js刷新验证码

  return $this->render('index', array('model' => $model));

<?php/** * Created by PhpStorm. * User: flying * Date: 2016/10/23 * Time: 15:44 */namespace app\modules\controllers;use yii\web\Controller;use app\models\LoginForm;use yii\filters\AccessControl;use yii\filters\VerbFilter;class LoginController extends Controller{    /**     * @inheritdoc     */    public function behaviors()    {        return [            'access' => [                'class' => AccessControl::className(),                'only' => ['logout'],                'rules' => [                    [                        'actions' => ['login', 'error', 'captcha'],//【增加login】                        'allow' => true,                        'roles' => ['@'],                    ],                ],            ],            'verbs' => [                'class' => VerbFilter::className(),                'actions' => [                    'logout' => ['post'],                ],            ],        ];    }    /**     * @inheritdoc     */    public function actions()    {        return [            'error' => [                'class' => 'yii\web\ErrorAction',            ],//            'captcha' => [//                'class' => 'yii\captcha\CaptchaAction',//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,//            ],
    //增加captcha            'captcha' => [                'class' => 'yii\captcha\CaptchaAction',                'maxLength' => 4,                'minLength' => 4            ],        ];    }    public function rules()    {
       //返回/增加  这两项captcha
return [
            ['verifyCode', 'required'],            ['verifyCode', 'captcha'],        ];    }    public function actionIndex()    {        $model = new LoginForm;        // Uncomment the following line if AJAX validation is needed        // $this->performAjaxValidation($model);        if (isset($_POST['LoginForm'])) {            $model->attributes = $_POST['LoginForm'];            p($model);        }
//必须用render,否则不能刷新验证码,因为不能调用框架的js/jquery代码        return $this->render('index', array('model' => $model));    }}

3. 模型:LoginForm.php

1. 添加成员变量:public $verifyCode;

2.rules增加以下内容,指定模块和控制器

['verifyCode', 'captcha', 'message'=>'验证码错误', 'captchaAction'=>'/test/login/captcha'],

   3. attributeLabels添加:
  'verifyCode' => '验证码', //【验证码添加项目】,验证码的名称,根据个人喜好设定

<?phpnamespace app\models;use Yii;use yii\base\Model;/** * LoginForm is the model behind the login form. * * @property User|null $user This property is read-only. * */class LoginForm extends Model{    public $username;    public $password;    public $rememberMe = true;    public $verifyCode;//【验证码添加项目】    private $_user = false;    /**     * @return array the validation rules.     */    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'],            ['verifyCode', 'captcha', 'message'=>'验证码错误', 'captchaAction'=>'/test/login/captcha'],//指定模块、控制器        ];    }    /**     * 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 boolean 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     */    public function getUser()    {        if ($this->_user === false) {            $this->_user = User::findByUsername($this->username);        }        return $this->_user;    }    public function attributeLabels()    {        return [            'username' => '用户名:',            'password' => '密码:',            'rememberMe' => '是否记住密码',            'verifyCode' => '验证码', //【验证码添加项目】,验证码的名称,根据个人喜好设定        ];    }}


1 0
原创粉丝点击