Yii2 需要在更新时验证 [英] Yii2 required validation on update

查看:31
本文介绍了Yii2 需要在更新时验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Yii2 表单,其中包含取决于页面操作的表单字段.前任.当操作为 create 时很少出现字段,当操作为 update 时出现很少的字段.我想根据这种情况添加必需的验证.

I've Yii2 form containing form fields depending on action of page. Ex. Few fields appears when then action is create and few appears when action is update. I want to add required validation based on this scenario.

例如

<?= $form->field($model, 'unique_identifier')->textInput(['maxlength' => 45]) ?>

我仅在 action => 时显示此字段;'更新'.

现在我想为此添加必需的验证,我尝试了这个:

Now I want to add required validation for this and I tried this:

[['unique_identifier'], 'required', 'on' => 'update'],

但上面的验证不起作用.如果我删除 on=>update 那么它会在创建和更新场景中进行验证.

But above validation not working. If I remove on=>update then its validating on both create and update scenario.

任何帮助将不胜感激.

推荐答案

ActiveRecord 在您更新或创建项目时不会自动设置方案.您必须覆盖模型中的 update() 方法并设置您需要的场景.例如.你的情况

ActiveRecord does not set scenario automaticaly when you update or create items. You must override update() method in your model and set scenario that you need. E.g. in your case

public function update($runValidation = true, $attributeNames = null)
{
    $this->scenario = 'update';
    return parent::update($runValidation, $attributeNames);
}

您也可以在 actionUpdate 中设置场景

Also you can set scenario in your actionUpdate

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $model->scenario = 'update';
    //load data from request, save model etc.
 }

这篇关于Yii2 需要在更新时验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆