[英]Yii2 Models Validations
I am working on Yii2, however I have a model this model have some attributes, some are required on insert/create mode and some are required on update mode, let say mode = scenario, So I created a Form model with 2 scenarios insert and update, then I set validation rules for the attributes as the scenario, the question is: shall I define the scenarios in both models(Active Record and Form Model)? 我正在研究Yii2,但是我有一个模型这个模型有一些属性,有些在插入/创建模式下是必需的,有些在更新模式下是必需的,比如mode = scenario,所以我创建了一个带有2个场景插入的表单模型更新,然后我将属性的验证规则设置为场景,问题是:我应该在两个模型中定义场景(活动记录和表单模型)吗?
Thank you in advance. 先感谢您。
Scenarios should be defined in your model .. 应在您的模型中定义方案..
and you should set the scenario youwant use in your related action 并且您应该在相关操作中设置您想要使用的方案
public function actionUpdate(){
....
$model->scenario = 'update';
...
ActiveRecord read from the database has the "update" scenario, while a new record has the "insert" scenario.
$modelA = User::model()->findByPk(1); // $model->scenario = 'update'
$modelB = new User(); // $model->scenario = 'insert'
$modelB->scenario = 'light'; // custom scenario
if ($modelB->validate()) { // will only apply rules of the "light" scenario
...............
..............
}
You can do so, in your model: 你可以在你的模型中这样做:
class YourModel extends \yii\db\ActiveRecord
{
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
...
public function scenarios(){
$scenarios = parent::scenarios();
$scenarios[static::SCENARIO_CREATE] = ['field_1', 'field_2'];
$scenarios[static::SCENARIO_UPDATE] = ['field_1', 'field_3'];
return $scenarios;
}
...
}
In Your conttroller: 在您的控制器中:
class YourController extends Controller {
...
public function actionCreate(){
$model = new YourModel()
$model->scenario = YourModel::SCENARIO_CREATE;
if($model->validate()){ // validate fields specifed in YourModel SCENARIO_CREATE
...
}
...
}
...
public function actionUpdate(){
$model = new YourModel()
$model->scenario = YourModel::SCENARIO_UPDATE;
if($model->validate()){ // validate fields specifed in YourModel SCENARIO_UPDATE
...
}
...
}
}
If my answer helpful, please put a tick)) 如果我的回答有帮助,请勾选))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.