The situation is as follows. There is a file field that loads the file and saves the file name to the database. If I edit an entry that already contains a file that was previously uploaded, but leaves the file field intact (for example, only the title needs to be changed), then the corresponding field in the database becomes empty. In addition, if the field is required, the form generally refuses to be sent, requiring you to upload a new file. What is the right thing to do in this situation?

Update : I will add the code of my actionUpdate, which would be clearer (on the advice of @YaroslavMolchan).

public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post())) { $directory = Service::getFileDirectory(); $mainImage = UploadedFile::getInstance($model, 'main_image'); if ($mainImage) { $uid = uniqid(time(), true); $model->main_image = $uid . '.' . $mainImage->extension; $mainImage->saveAs($directory . $model->main_image); } if ($model->save()) return $this->redirect(['view', 'id' => $model->id]); } return $this->render('update', [ 'model' => $model, ]); } 

    1 answer 1

    I see 2 options.

    The first option: in the place where you save the data, just check if the field is filled, if yes, then download it and update the file name in the database:

     if ($form->validate()) { if ($form->fileName) { //Грузим файл и пишем в модель } } 

    The second option: for example, a field in the table you have a fileName on the form you create a file field and also if the field is filled in, save it and transfer the value to $model->fileName and thus if the field is empty you will not write it to the database, because different names, for example:

     if ($form->validate()) { if ($form->file) { //Грузим файл и пишем в модель $path = '/path/to/file.jpg'; $form->file->saveAs($path); $user->fileName = $path; } } 

    I think you understand the essence, but in general it is better to show more code.

    • Thanks for the answer. I can think of ways around this problem. Simply, I was hoping that the framework provides for such cases, but I just do not know such mechanisms. I tried to use the property skipOnEmpty, but it did not help. I did this: [['main_image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg'], By the way, I added the code to the text of my main question, for clarity - Skiv
    • @Skiv is easier to create a pure model for validation, and then there will be no problems with an empty field and then transfer the data to the ActiveRecord model, perhaps then skipOnEmpty work - Yaroslav Molchan