`Skip on empty` does not work in loading Yii2 file

I have a suggestion to upload a logo for companies in my application. Loading and saving when creating a profile work fine. But when updating, the logo remains blank if I do not download it again!

Here is my update form

<?php $form = ActiveForm::begin([ 'options' => ['enctype'=>'multipart/form-data'] ]); ?> ..... <?= $form->field($model, 'logo')->fileInput() ?> ... 

My controller action

  if ($model->load($_POST) ) { $file = \yii\web\UploadedFile::getInstance($model, 'logo'); if($file){ $model->logo=$file; } if($model->save()){ if($file) $file->saveAs(\Yii::$app->basePath . '/web/images/'.$file); } return $this->redirect(['profile']); } else { return $this->renderPartial('update', [ 'model' => $model, ]); } 

My rules:

 public function rules() { return [ [['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true], [['name'], 'required'], [['name', 'description'], 'string'], ]; } 

Any ideas ????

+6
source share
2 answers

skipOnEmpty is not applied here, because in the update action the attribute $model->logo will not be empty, it will be a line with the file name. $file is still an array with only keys, but no if value is not loaded again. So check $file->size instead of checking !empty($file) . Bug fixed by changing the controller code as follows:

  $model = $this->findModel($id); $current_image = $model->featured_image; if ($model->load(Yii::$app->request->post())) { $image= UploadedFile::getInstance($model, 'featured_image'); if(!empty($image) && $image->size !== 0) { //print_R($image);die; $image->saveAs('uploads/' . $image->baseName . '.' .$image->extension); $model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension; } else $model->featured_image = $current_image; $model->save(); return $this->redirect(['update', 'id' => $model->module_id]); } else { return $this->render('add', [ 'model' => $model, ]); } 
+9
source
 'skipOnEmpty' => !$this->isNewRecord 

You can skip it to update.

+1
source

Source: https://habr.com/ru/post/973634/


All Articles