You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:22:40