Yii2简单实现给表单添加验证码的方法

原创 2016-12-30 16:01:12 489
摘要:本文实例讲述了Yii2简单实现给表单添加验证码的方法。分享给大家供大家参考,具体如下:控制器SiteController:class SiteController extends Controller {   // ...   public function actions()  &nbs

本文实例讲述了Yii2简单实现给表单添加验证码的方法。分享给大家供大家参考,具体如下:

控制器SiteController:

class SiteController extends Controller
{
  // ...
  public function actions()
  {
    return [
      // ...
      'captcha' => [
        'class' => 'yii\captcha\CaptchaAction',
        'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
      ],
    ];
  }
  // ...
}
?>

定义表单Model:

class ContactForm extends Model
{
  // ...
  public $verifyCode;
  // ...
  public function rules()
  {
    return [
      // ...
      ['verifyCode', 'captcha'],
    ];
  }
  // ...
}
?>

在view中调用方法:

$form = ActiveForm::begin(['id' => 'contact-form']); ?>
// ...
$form->field($model, 'verifyCode')->widget(Captcha::className()) ?>
// ...
ActiveForm::end(); ?>

更多关于Yii2简单实现给表单添加验证码的方法请关注PHP中文网(www.php.cn)其它文章!

发布手记

热门词条