Hello, I use the FileInput widget to upload thumbnails to a post . Creating / editing / etc entries is done using CRUD.

The fact is that when the record update form is loaded, the image name in the database is not loaded, unlike other fields.

Show url

Suppose the image and all other fields are filled and we decided to edit the field blocks .

  1. Go to edit the record.
  2. Replacing the contents of the field blocks .
  3. We save.

Since the thumbnail field is empty - null will be saved instead of the current content.

Actually, I want to solve this problem. So far, the options to make a separate function for updating / adding / removing thumbnails, but this is an extreme option. I think someone has met with this problem and I hope that he can help me.

Here is the part of the code that is responsible for displaying the image upload form:

 <?= $form->field($model, 'miniature')->widget(FileInput::classname(), [ 'options' => ['accept' => 'image/*'], ]); ?> 

The function of saving the image in the model:

 public function beforeSave($insert) { if ($file = UploadedFile::getInstance($this, 'miniature') ){ $dir = Yii::getAlias('@frontend').'/web/upload/'; $this->miniature = time().'.'.$file->extension; $file->saveAs($dir.$this->miniature); } return parent::beforeSave($insert); } 

    1 answer 1

    You need to check whether the value is empty or not.

    If not empty, fill in the new data with the old value. Of course, provided that you have not transferred the new value. Code:

     public function beforeSave($insert) { if(!$this->isNewRecord && self::getOldAttribute('miniature') != ''){ $this->miniature = self::getOldAttribute('miniature'); } return parent::beforeSave($insert); }else{ // Код сохранения нового изображения } 

    Solution via slo_nik .