I had a difficulty: when updating, the user must download the file again, the old one will be deleted, and the new name will be written into the database.
But to change any information you have to re-upload the file, which is quite inconvenient.
In the model there is a mandatory file download:

array('filename', 'file', 'types'=>'rar, zip, 7z','allowEmpty'=>false,'maxFiles' => 1,'message'=>'Допустимые типы к загрузке: rar, zip, 7z'), 

How to make that if the file is not selected, then the file recording would not be made, and vice versa, respectively?

Update (controller code):

 $model=$this->loadModel($id); $model->scenario='update'; if(isset($_POST['ModsManage'])) { $set_info = ModsManage::model()->findByPk($id); $model->attributes=$_POST['ModsManage']; if(CUploadedFile::getInstance($model,'filename')){ $model->filename = CUploadedFile::getInstance($model,'filename'); }else{ $model->filename = $set_info->filename; } if($model->save()){ if(CUploadedFile::getInstance($model,'filename')){ if(file_exists(Yii::getPathOfAlias('webroot').'/mods/'.$model->id.'/'.$set_info->filename)){ unlink(Yii::getPathOfAlias('webroot').'/mods/'.$model->id.'/'.$set_info->filename); } $path=Yii::getPathOfAlias('webroot').'/mods/'.$model->id.'/'.$model->filename->getName(); $model->filename->saveAs($path); } //$this->redirect(array('mod','id'=>$model->id)); } } $this->render('update',array( 'model'=>$model, )); 

    1 answer 1

    As far as I understand, you need to implement two things:

    1. Set allowEmpty => true in validation rules. This will allow you to dump a model without the uploaded file.
    2. Implement save logic that will not write a file field if it is empty. Without additional code it is difficult to say exactly how to do it, but the easiest way is simply not to overwrite the loaded model field.
    • array ('filename', 'file', 'types' =>' rar, zip, 7z ',' allowEmpty '=> false,' maxFiles' => 1, 'message' => 'Valid download types: rar, zip, 7z, 'on' => 'create'), array ('filename', 'file', 'types' => 'rar, zip, 7z', 'allowEmpty' => true, 'maxFiles' => 1, 'message' => 'Acceptable download types: rar, zip, 7z', 'on' => 'update'), and in the controller I call the necessary scripts, update to check if the file is loaded, but if the file is not loaded , I do $ model-> filename = $ set_info-> filename; then comes save (), but why it writes down the empty field. When updating with the file everything is fine - innot20
    • What is set_info? - etki
    • $ set_info = ModsManage :: model () -> findByPk ($ id); gets what is already recorded (used to delete the old file if the new one is loaded) - innot20
    • @ innot20 check that the validation rules are safe for the filename field - etki