菜鸟CK 2016-07-08 23:03:46 4742次浏览 4条评论 7 2 0

新建CodeController.php控制器。

<?php

namespace app\controllers;

use yii\web\Controller;

class CodeController extends Controller{

	public function actionVerifyCode(){
		
	}
}

新建Code.php模型。

<?php

namespace app\models;

use yii\base\Model;

class Code extends Model{

	public $code;

	public function rules(){
		return [
			['code','captcha','captchaAction' => 'code/captcha','message' => '验证码错误!']
		];
	}
}

新建视图@views/code/verifycode.php

<?php
use \yii\helpers\Html;
?>

修改Code控制器actionVerifyCode操作和新增actions方法

<?php

namespace app\controllers;

use yii\web\Controller;

class CodeController extends Controller{

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

	public function actionVerifyCode(){
		$model = new \app\models\Code();
		if(\Yii::$app->request->isPost && $model->load(\Yii::$app->request->post())){
			if($model->validate()){
				echo '验证成功!';
			}else{
				var_dump($model->getErrors());
			}
		}
		return $this->render('verifycode',['model'=>$model]);
	}
}

修改视图代码,加载模型数据和验证码

<?php
use \yii\helpers\Html;
?>

<?=Html::beginForm('','post')?>
	<?=\yii\captcha\Captcha::widget([
			'model' 		=> $model,
			'attribute' 	=> 'code',				//表单字段
			'captchaAction' => 'code/captcha',  	//与模型关联的验证码操作,由actions()定义
			'template' 		=> '{input}{image}',    //模板,可以自定义
			'options' 		=> [					//input属性数组
				'class' => 'form-control',
				'id'	=> 'verify'
			],
			'imageOptions' => [						//image属性数组
				'class' => 'imageCode',
				'alt' 	=> '点击图片刷新'
			]
		]);
	?>
	<?=Html::submitButton('验证',['class' => 'btn btn-primary'])?>
<?=Html::endForm()?>

访问http://localhost/yii2/web/index.php?r=code/verify-code:
captcha.png

觉得很赞
您需要登录后才可以评论。登录 | 立即注册