how to use required on insert validator for yii2?

为君一笑 提交于 2019-12-12 08:57:34

问题


Can anyone have a suggestion about how to use "on" => "insert" validation in yii2? I have used

array('field_name', 'required', 'on'=>'insert')

in Yii1 but in yii2 it does not check if I set

['field_name', 'required', 'on'=>'insert']

. What is the problem here can you please explain? Thanks in advance.


回答1:


You should simply set your model's scenario before validation :

$model->scenario = 'insert';

Since with Yii2 :

By default, a model supports only a single scenario named default

Read more : http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios




回答2:


First define the scenario:

// scenario is set as a property
$model->scenario = 'insert';

OR

// scenario is set through configuration
$model = new User(['scenario' => 'insert']);

Then you may specify the rule as:

// for single field
['field_name', 'required', 'on' => 'insert'],

// for multiple fields
[['field_name1','field_name2'], 'required', 'on' => 'insert'],

For more details check: http://www.yiiframework.com/doc-2.0/guide-structure-models.html#validation-rules



来源:https://stackoverflow.com/questions/28981062/how-to-use-required-on-insert-validator-for-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!