Yii2框架Users模块登录表单验证码功能失效问题及解决
问题:用户模块登录表单验证码失效,其他表单正常
我在应用的其他表单中实现的验证码字段可正常工作,但在Users模块的登录表单中,验证码功能失效。
相关代码
登录表单代码
<?= $form->field($user, 'captcha')->widget(\yii\captcha\Captcha::className(), [ 'captchaAction' => 'user/captcha', // Important, otherwise no image shown. 'template' => '...', ]); ?>
User模型代码
class User extends ActiveRecord implements IdentityInterface { public $captcha; public function rules() { return [ ... /* Modified after the suggestion of Michal Hynčica. */ /* I tried also 'users/user/captcha'. */ ['captcha', 'captcha', 'captchaAction' => 'user/captcha'], ]; } }
UserController的actions()方法
public function actions() { return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', ], ]; }
UserController的behaviors()方法
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['captcha'], 'allow' => true, ], ], ] ]; }
问题解决方法
由于User模型中存在多个场景,需要将captcha字段添加到登录场景中:
public function scenarios() { return [ ... self::SCENARIO_LOGIN => ['name', 'password', 'remember', 'captcha'], ]; }
内容的提问来源于stack exchange,提问作者anva
相关产品推荐
相关产品推荐

