A good time of day is a question such as linking an image to an article from a form.

I used the standard method yii2;

ImageFile field; in the database, in the same table, created the imageFile field;

I have the following in the controller

if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->imageFile = UploadedFile::getInstance($model, 'imageFile'); if ($model->imageFile) { $model->upload(); } return $this->redirect(['view', 'id' => $model->id]); 

Loading method - standard

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

Images from the form are perfectly loaded, but when I see what comes in the post, in the field imageFile sting 0

and I need to bind the image in the database that was loaded. Please tell me how to do this, or where to read, see.

    1 answer 1

    You have implemented the file download, it remains to implement the save in the database the name of this file. For example, in the database you have an image field in the model, just declare a public imageFile field

     class TableName extends ActiveRecord{ public $imageFile; ... 

    In the controller, approximately the following logic:

    • load $ _POST data into the model
    • get file information ( UploadedFile::getInstance() )
    • validate the model
    • load file and add file name to base field
    • save model

    About:

     if ($model->load(Yii::$app->request->post())) { $model->imageFile = UploadedFile::getInstance($model, 'imageFile'); if($this->validate()){ if ($model->imageFile && $model->upload()) { $model->image = $this->imageFile->baseName . '.' . $this->imageFile->extension; } if($this->save()){ return $this->redirect(['view', 'id' => $model->id]); } } 
    • Aha, I understood, otherwise I had a problem in getting a name, since I was still a lamer) Now I will rewrite a little, thanks - mydls1
    • persists. I assume that the data that is stored is stored in ["_attributes": "yii \ db \ BaseActiveRecord": private] =>, and $ model-> image a higher level - mydls1
    • can you tell? I will be grateful - mydls1
    • @ mydls1 what exactly? is everything saved? from the picture, the feeling that you declared an image in the model is simple, and you did not add it to the table + it was registered in the rules - Bookin