I have a provision to upload logo for companies in my application. Uploading and saving on creating profile works fine. But on update, logo goes empty if I am not uploading
'skipOnEmpty' => !$this->isNewRecord
For update it can be skipped.
skipOnEmpty
does not apply here because in the update action the $model->logo
attribute will not be empty, it will be a string with the file name.$file
is still an array with only keys, but not values if not uploaded again. So checked the $file->size
instead of checking !empty($file)
. Fixed the issue by modifying 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,
]);
}