I'm trying to deal with yii2 and made crud news on the manual, everything works. Now I’m trying to tie the image downloader to the news and don’t figure out how to correctly enter the code from the manual for uploading the file to the controller action:

public function actionCreate() { $model = new GoodsCatalog(); if (Yii::$app->request->isPost) { $model->imageFile = UploadedFile::getInstance($model, 'imageFile'); if ($model->upload()) { // file is uploaded successfully return; } } if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } 

I understand what is wrong, please tell me how to combine the code for downloading a file with an existing one?

    1 answer 1

    Well, for example like this.

      public function actionCreate() { $model = new Settings(); if ($model->load(Yii::$app->request->post())) { $file = UploadedFile::getInstance($model, 'file'); if (isset($file)) { $filename = uniqid() . '.' . $file->extension; $path = 'uploads/'.$filename; if ($file->saveAs($path)) { $model->file = $path; $model->value = $path; } } if ($model->save()) { Yii::$app->session->setFlash('info', 'Запись успешно добавлена'); return $this->redirect(['index']); } else{ foreach($model->errors as $error) Yii::$app->session->setFlash('error', $error); return $this->redirect(['index']); } } else { foreach($model->errors as $error) Yii::$app->session->setFlash('error', $error); return $this->redirect(['index']); } } 

    Before this, declare a variable in the model.

     public $file; 

    in the rules

      [['file'], 'file'], 

    And in the view, use the file attribute already.

     $form = ActiveForm::begin([ 'options' => ['enctype' => 'multipart/form-data']]); <?= $form->field($model, 'file')->fileInput(); ...