验证码比较麻烦,在三部分各有体现
controller
<?php namespace appcontrollersdemo_code; use yiiwebController; class DemoController extends Controller{ //重写actions类 public function actions(){ return [ 'captcha'=>[ //初始化一个CaptchaAction类,并写验证码的一些参数 'class' => 'yiicaptchaCaptchaAction', 'maxLength'=>4, 'minLength'=>4, 'height'=>40, 'width'=>80, ], ]; }
//调用 public function actionIndex(){ $code = new appmodelsdemo_codecode; return $this->render('view',['code'=>$code]); } } ?>
model
<?php namespace appmodelsdemo_code; use yiiaseModel; class code extends Model{ //初始化一个变量,其实就是验证码 public $verify_code; public function rules(){ return [ //对上面变量的字段进行验证
//captchaAction是controller里面的 ['verify_code','captcha','captchaAction'=>'demo_code/demo/captcha'], ['verify_code','required','message'=>'不能为空'] ]; } } ?>
view
<?php echo yiicaptchaCaptcha::widget([ 'model'=>$code,//controller传过来的参数 'attribute'=>'verify_code',//model开启验证字段名字 'captchaAction'=>'demo_code/demo/captcha',//验证字段的方法,对应controller的action的namespace 'options'=>['id'=>'input'],//填写一些其他信息,比如class 'imageOptions'=>['alt'=>'点击刷新'],//图片的属性 ]); ?>