Yii2 required verification during upgrade

I have a Yii2 form containing form fields depending on the action of the page. Ex. Few fields appear when the create action is then, and several appear when the update action. I want to add the required validation based on this scenario.

Ref.

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

I show this field only when action => 'update' .

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

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

But the above verification does not work. If I remove on=>update , then its verification is performed both during creation and during update.

Any help would be appreciated.

+5
source share
1 answer

ActiveRecord does not automatically install the script when updating or creating items. You must override the update() method in your model and install the script that you need. For instance. in your case

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

You can also set the script in actionUpdate

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

All Articles