public function actionCreate() { $model = new Image(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $file = UploadedFile::getInstance($model, 'name'); if ($fileModel = FileModel::saveAs($file, '@common/upload')) { } if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->saveUploadedFile() !== false) { $model->save(); return $this->redirect('image/create', ['model' => $model]); } } else { return $this->render('create', ['model' => $model]); } } }
public function saveUploadedFile($deleteOldFile = true) { /* @var $file UploadedFile */ $file = $this->{$this->attribute}; if ($file !== null) { $model = FileModel::saveAs($file, $this->uploadPath, $this->directoryLevel); if ($model) { if ($this->savedAttribute !== null) { if ($deleteOldFile === null) { $deleteOldFile = $this->deleteOldFile; } $oldId = $this->owner->{$this->savedAttribute}; $this->owner->{$this->savedAttribute} = $model->id; if ($deleteOldFile && ($oldModel = FileModel::findOne($oldId)) !== null) { return $oldModel->delete(); } } return true; } return false; } }