Yii2.0同一个页面使用多个验证码

来源:互联网 发布:vb语言程序设计 编辑:程序博客网 时间:2024/06/11 06:37

Yii2.0框架对实现的抽象层次很高,导致我们使用的时候完全跟着文档走,但是文档又写的很粗糙,我个人认为,写Yii2.0的人不喜欢写文档,希望我们自己去读源码。
如果需要在同一个页面,使用不同的验证码,怎么办?这个就要根据验证码的机制来找答案了。
先看看验证码的使用方法:

在需要使用验证码的比如User控制器中的actions方法中添加设置:
public function actions() {
return [
‘captcha’ => [
‘class’ => ‘yii\captcha\CaptchaAction’,
‘height’ => 50,
‘width’ => 80,
‘minLength’ => 4,
‘maxLength’ => 4
],
];
}

然后就可以在视图中加入验证码了。

<?php use yii\captcha\Captcha; echo $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className(),['captchaAction'=>'user/captcha','imageOptions'=>['alt'=>'点击换图','title'=>'点击换图','style'=>'cursor:pointer',]]);?>

在User控制器中验证验证码是否正确:

$this->createAction('captcha')->validate($captchCode, false); //$captchCode为用户输入的验证码

那么,我们如果要在同一个页面中使用2个验证码,怎么办呢?
其实只需要在actions里设置两个action就可以了:

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

试图中:

<?php use yii\captcha\Captcha; echo $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className(),    [    'captchaAction'=>'user/captcha1',    'imageOptions'=>[    'alt'=>'点击换图',    'title'=>'点击换图',    'style'=>'cursor:pointer',    ]]);echo $form->field($user_login,'captcha')->widget(yii\captcha\Captcha::className(),    [    'captchaAction'=>'user/captcha2',    'imageOptions'=>[    'alt'=>'点击换图',    'title'=>'点击换图',    'style'=>'cursor:pointer',    ]]);?>

验证同理可得:

$this->createAction('captcha1')->validate($captchCode1, false); //$captchCode1为用户在第一个验证码input中输入的验证码$this->createAction('captcha2')->validate($captchCode2, false); //$captchCode2为用户在第二个验证码input中输入的验证码
原创粉丝点击