Yii2 $model->load($request->post()) returns false when uploading files


(smohadjer) #1

I have an ActiveRecord model that I use to upload files. However when I upload a file in my action the code in below “if” section doesn’t run due to $model->load($request->post()) returning false:

$request = Yii::$app->request;
$model = new EventAttachments();
if ($model->load($request->post())) {
    echo 'It works!';
}

Any idea why load returns false?


(stitch) #2

Hi. Read this maybe it help you.


(smohadjer) #3

I had read that, but I didn’t know that $_POST will be empty when uploading files and hence loading it will return false. Thanks.


(stitch) #4

I doubt that you read the article. Because there are no references to

$model->load($request->post())

or something similar.

In the article shown:

public function actionUpload()
    {
        $model = new UploadForm();

        if (Yii::$app->request->isPost) {
            $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
            if ($model->upload()) {
                // file is uploaded successfully
                return;
            }
        }

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

Read very attentively the article and act in the same way


(smohadjer) #5

I had noticed that this article uses isPost() instead of load($request->post()), but didn’t know why and since in my upload form I had other fields which I also wanted to be posted I thought I could use the load approach (which other articles use). Unfortunately load approach only works if user is posting at least one other field, so I have switched to isPost() and now things are working as expected. :slight_smile: