一、不需要对CCaptchaAction产生的验证码进行其他javascript操作时,用下面的方法就行了:
1、在控制器Controller中添加
class RegistrationController extends CController
{
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,//验证码背景颜色
'width'=>95,//验证码图片的宽度
'height'=>35,//验证码图片的高度
),
);
}
}
2、在显示验证码的视图view中添加
<?php $this->widget('CCaptcha',array(
'showRefreshButton'=>true,
'clickableImage'=>false,
'buttonLabel'=>'刷新验证码',
'imageOptions'=>array(
'alt'=>'点击换图',
'title'=>'点击换图',
'style'=>'cursor:pointer',
'padding'=>'10')
));
?>
具体的各个参数意思可参考framework/web/widgets/captcha/CCaptchaAction.php
3、需要在模型model里面添加
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
public $verifyCode;
private $_identity;
public function rules(){
return array(
array('username','required','message'=>'登录帐号不能为空'),
array('password','required','message'=>'密码不能为空'),
array('verifyCode','required','message'=>'验证码不能为空'),
array('verifyCode','captcha', 'on'=>'login','allowEmpty'=>!Yii::app()->admin->isGuest),
array('rememberMe', 'boolean'),
array('password', 'authenticate'),
);
}
public function attributeLabels()
{
return array(
'rememberMe'=>'下次记住我',
'verifyCode' =>'验证码'
);
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','帐号或密码错误.');
}
}
}
这样3步基本上就可以实现yii自带的widget的验证码功能了
但是,出于实际需要,我们有时候要实现一些javascript功能:如鼠标离开验证码输入框时就要马上对验证码进行异步验证,这时候上面的方法就做得还不够了
二、需要对CCaptchaAction产生的验证码进行其他javascript操作时,可用下面的方法
在一的基础上,$this->createAction('captcha')->getVerifyCode()这样就可以取出生成的验证码的具体code了,可以进行方便的javascript异步操作了,很多同学一开始会忽略通过
createAction的方法来创建动作实例,这是需要注意的,当然这点很多视频教程官方文档什么的都没详细说,我们可以通过查看framework/web/CController.php的具体实现来查看。