S
S
Svyatoslav Pintokha2015-12-08 17:11:28
Yii
Svyatoslav Pintokha, 2015-12-08 17:11:28

What is wrong with uploading files?

The error is simple, but somehow I don’t understand)
Required parameters are missing: id

public function actionCreate()
    {
        $model = new Advertisement();

        if ($model->load(Yii::$app->request->post())) {
            $imagesArray = UploadedFile::getInstances($model, 'image');
            foreach ($imagesArray as $file) {
                $name = \Yii::$app->security->generateRandomString(7).'.jpg';
                $file->saveAs(Url::to('@common/files/advertisement/' . $name));
                $add = new Advertisement_Image();
                $add->advertisement_id = $model->id;
                $add->image = $name;
                $add->save();
            }
            $model->author = Yii::$app->user->id;
            $model->save();

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korovin, 2015-12-09
@vakorovin

Good afternoon. Read your code in order.
We created a new object of the Advertisement class, loaded POST parameters into it, and then, without SAVING it yet, ran through the files in a loop and each Advertisement_Image object was written in the advertisement_id "$ model-> id", and where does the id of the model come from before it is saved to the database ? That is the problem. Save related files after saving $model.
And a couple more recommendations: take a look at www.php-fig.org/psr , it will not be superfluous (code style). We would put the files not in common, but in frontend.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question