yii2验证码的一些心得

1.在控制器中加入

public function actions() {
        return [
            'captcha' =>  [
                'class' => 'yii\captcha\CaptchaAction',
                'height' => 50,
                'width' => 80,
                'minLength' => 4,
                'maxLength' => 4
            ],
        ];
    }

2.如果数据库没有验证码的字段记得先声明一个验证码的模型

 public  $verifyCode;

在models模型的rules方法中加入

 public function rules()
    {
        return [

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

        ];
    }

captchaAction 指定captcha所在的控制器路径,默认是‘site/captcha’,不换到指定位置的话,很容易,验证码就显示不出来。
3.然后在models模型中加入

 public function attributeLabels()
    {
        return[
            'verifyCode'=>"验证码",
        ];
    }

4接下来是视图view中加入

<?php 
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
?>
在添加验证码的时候加入
<?php 
echo $form->field($model,'verifyCode',[ 'template'  =>
                   '<div  class="row cl"><div class="formControls col-8 col-offset-3">{input}'.Captcha::widget([
                       'model' =>$model,
                       'attribute' =>'verifyCode',//模型中也要申明
                       'captchaAction' =>'index/captcha',//指定操作
                       'template'  =>'{image}',//image代表此处生成验证码图片
                       'imageOptions'   =>[
                           //以下atrribute属性,可自己扩展
                           'title'  =>'点击刷新''style' =>'margin-left:20px;'
                       ],
                   ]).'{error}</div></div>'])->textInput(['class'=>'input-text size-L','placeholder'=>'验证码','style'=>'width:150px,padding-left:25px']);?>

imageOptions设定一些参数,例如 手势,提示等等。
对应布局中,如下:以确保你在点击验证码可以自动刷新

<?php $this->beginPage() ?>
<?php $this->beginBody() ?>
//your codes...
<?= $contents; ?>
//your codes...
<?php $this->endBody() ?>
<?php $this->endPage() ?>

最后,控制器中调用render而非renderPartial

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

刷新验证码不更新的解决方法

猜你喜欢

转载自blog.csdn.net/php12345679/article/details/82384119