R
R
Ruslan Tilyaev2019-09-06 21:16:40
Yii
Ruslan Tilyaev, 2019-09-06 21:16:40

Why is the image not loading into the database?

Good time of day! Faced such a problem that the path and name of the image are not loaded into the database, while it is loaded on the server) YII2.
view:

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'img')->fileInput() ?>
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>

model:
public $img;

public function rules()
    {
        return [
            [['img'], 'file', 'extensions' => 'png, jpg']
        ];
    }

public function upload(){
        if($this->validate()){
            $path = 'images/' . $this->img->baseName . '.' . $this->img->extension;
            $this->img->saveAs($path);
            return true;
        }else{
            return false;
        }
    }

controller:
public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //загрузка картинки
            $model->img = UploadedFile::getInstance($model, 'img');
            if ($model->img) {
                $model->upload();
            }

            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question