Yii2簡(jiǎn)單實(shí)現(xiàn)給表單添加驗(yàn)證碼的方法

字號(hào):


    本文實(shí)例講述了Yii2簡(jiǎn)單實(shí)現(xiàn)給表單添加驗(yàn)證碼的方法。分享給大家供大家參考,具體如下:
    控制器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中調(diào)用方法:
    $form = ActiveForm::begin(['id' => 'contact-form']); ?>
    // ...
    $form->field($model, 'verifyCode')->widget(Captcha::className()) ?>
    // ...
    ActiveForm::end(); ?>
    希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。