验证码字段在 Yii2 中的模块上不起作用

问题描述 投票:0回答:1

我在申请表中有一个验证码字段,它可以正常工作,并且在

login
module
Users 形式中有一个,它不起作用。

login
形式我写了:

<?= $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'],
        ];
    }

actions()
UserController
方法中我写到:

public function actions()
{
    return [
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
        ],
    ];
}

我还在

behaviors()
方法中添加了这段代码,尽管在它工作的另一个控制器中,我没有写它:

public function behaviors()
{
   return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['captcha'],
                    'allow' => true,
                ],
            ],
        ]
   ];
}

解决了。在

User
模型中有一些场景,我不得不将“验证码”字段添加到
login
场景:

public function scenarios()
{
    return [
        ...
        self::SCENARIO_LOGIN => ['name', 'password', 'remember', 'captcha'],
    ];
}
module yii2 captcha
1个回答
1
投票

如果您使用与默认

site/captcha
不同的验证码操作的验证码,您也必须在验证规则中设置
$captchaAction
属性。所以,在你的用户模型中:

class User extends ActiveRecord implements IdentityInterface
{
    public $captcha;

    public function rules()
    {
        return [
            // ...
            ['captcha','captcha', 'captchaAction' => 'users/user/captcha'],
        ];
    }

这是因为

yii\captcha\CaptchaAction
在会话中存储数据时使用动作的唯一ID作为键。如果验证规则指向不同的验证码操作,它将无法正确验证代码。

© www.soinside.com 2019 - 2024. All rights reserved.