问题
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