//控制器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(); ?>