php - Yii2 $model->save() 和验证码验证规则不起作用
问题描述
尽管有很多关于 Yii2 验证码以及保存问题的问题,但我找不到并回答解决了我的问题。希望有人可以提供帮助:
在我的网站中,我包含了一个联系表格和一个验证码。因此,我向模型、IndexController 和此处描述的表单添加了代码:https ://yii2-cookbook-test.readthedocs.io/forms-captcha/#how-add-captcha-to-a-form 验证 码如果代码输入不正确,则会显示并阻止提交表单。但是,如果我包含验证码验证规则,则消息不会保存到数据库中。所以验证规则似乎有问题。
['verifyCode', 'captcha', 'captchaAction' => '/contact/index/captcha']
我只是不明白这里有什么问题。当我将其注释掉时,模型已保存,但验证码未经过验证。留下带有“captchaAction”的部分会导致 Invalid Captcha ID 错误,解决方案是包含 captchaAction,如下所述:Yii2 Invalid CAPTCHA action ID in module
有谁知道这里可能出了什么问题?围着圈跑...
形式:
...
<div class="form-group">
<div><?= Yii::t('ContactModule.form', 'Please enter the letters from the image.'); ?></div>
<?= $form->field($model, 'verifyCode')->widget(Captcha::class, [
'captchaAction' => '/contact/index/captcha',
])->label(false); ?>
</div>
...
模型:
class Contact extends ActiveRecord{
public $verifyCode;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'contact';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name','email','message'], 'required'], //Checking that all the fields are required
['email', 'email'], // Validating that email is a valid email
[['name'],'string', 'max' => 50], //Verifying that name is not greater than its max length
[['email'], 'string', 'max' => 50], //Verifying that email is not greater than its max length
[['message'], 'string', 'max' => 255],//Verifying that message is not greater than its max length
['state', 'boolean'],
[['date'], 'date', 'format' => 'php:Y-m-d'],
['verifyCode', 'captcha', 'captchaAction' => '/contact/index/captcha'],
];
}
...
控制器
class IndexController extends Controller
{
public $subLayout = "@contact/views/layouts/default";
/**
* @inheritdoc
*/
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
]
];
}
/**
* Renders the index view for the module
*
* @return string
*/
public function actionIndex()
{
$model = new Contact();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->save();
...
解决方案
推荐阅读
- reactjs - 访问以对象为值的数组
- php - PHP - PL/SQL:如何将数组(作为 Oracle 过程的 OUT 参数)读入 PHP
- javascript - TypeError:prevState.blockHash 不可迭代
- python - Pandas - 作为字典的列 - 如何始终提取第一个元素
- angular - 垫选择下拉验证不适用于所选字段角度和材料
- javascript - 我可以在 SAP UI5 的标准消息框中提供链接吗?
- php - PHP 嵌套数组处理以创建日期键和值
- r - 查找自 R 以来的最小值
- javascript - 如何在单独的 tsx 文件中调用 React 钩子或修改单独函数之间的状态?
- python - 如何在 Pandas 的数据框的给定列中为每个唯一组件创建一个新列?