转自:http://www.yiichina.org/forum/thread-881-1-1.html
关于如果在表单中添加验证码(captcha),官方文档中一直没有的详细的介绍。下面就如何在YII blog的评论表单中添加验证码进行说明:
将以下代码插入评论的视图文件:views/comment/_form.php
<?php if (extension_loaded('gd')): ?>
<div class="row">
<?php echo CHtml::activeLabelEx($model, 'verifyCode') ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo CHtml::activeTextField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
在模型Comment.php中添加如下代码:
public $verifyCode;
在rules()下添加
array('verifyCode', 'captcha', 'allowEmpty'=>!Yii::app()->user->isGuest),
在attributeLabels()下添加:
'verifyCode' => 'Verification Code',
在控制器文件controllers/PostController.php 加添加如下动作:
public function actions() {
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
此时, 在 rules中,在 'deny all'前,增加如下代码:
array(
'allow',
'actions'=>array('captcha'),
'users'=>array('*'),
),
此时,可显示验证码。
非常好的例子,很详细,说到gd库和权限设置。
若您觉得我的博文对您有帮助,欢迎点击下方按钮对我打赏
打赏

