After a terrible day and a more productive night, I came across a solution that worked for me.
The main problem was that when updating the input file does not send its value (the name of the file stored in the database). It only sends information about the picture if it is viewed and selected by entering a file.
So, my workaround was to create another "virtual" field for controlling file upload called "upload_image". To do this, I simply added a public property with this name to my model class: public $upload_image;
I also add the following validation procedure to the Model class:
public function rules() { return [ [['upload_image'], 'file', 'extensions' => 'png, jpg', 'skipOnEmpty' => true], [['image'], 'required'], ]; }
Here "upload_image" is my virtual column. I added the “file” with “skipOnEmpty” = true, and the “image” is a field in my database, which should be necessary in my case.
Then, in my opinion, I set up the upload_image widget, for example:
echo FileInput::widget([ 'model' => $model, 'attribute' => 'upload_image', 'pluginOptions' => [ 'initialPreview'=>[ Html::img("/uploads/" . $model->image) ], 'overwriteInitial'=>true ] ]);
In the "initialPreview" option, I assign the name of my image stored in the "$ model-> image" property returned from the database.
Finally, my controller looks like this:
public function actionUpdate($id) { $model = $this->findModel($id); $model->load(Yii::$app->request->post()); if(Yii::$app->request->isPost){ //Try to get file info $upload_image = \yii\web\UploadedFile::getInstance($model, 'upload_image'); //If received, then I get the file name and asign it to $model->image in order to store it in db if(!empty($upload_image)){ $image_name = $upload_image->name; $model->image = $image_name; } //I proceed to validate model. Notice that will validate that 'image' is required and also 'image_upload' as file, but this last is optional if ($model->validate() && $model->save()) { //If all went OK, then I proceed to save the image in filesystem if(!empty($upload_image)){ $upload_image->saveAs('uploads/' . $image_name); } return $this->redirect(['view', 'id' => $model->id]); } } return $this->render('update', [ 'model' => $model, ]); }