Edgars Karlsons
Edgars Karlsons

Reputation: 23

How to upload images with tabular input in Yii2?

I´m struggling with tabular input and image upload. I´m not using any extensions/widgets. Form works perfectly, but - without image upload.

I created 2 models: EventForm (single form) and EventArtwork (can be multiple)

I have a function protected function handlePostSave, which I usually use like this in actions (eg actionCreate), but this doesn't work for arrays:

    protected function handlePostSave(EventArtwork $model)
    {
        if ($model->load(Yii::$app->request->post())) {
            $model->upload = UploadedFile::getInstance($model, 'upload');

            if ($model->validate()) {
                if ($model->upload) {
                    $filePath = 'uploads/' . $model->upload->baseName . '.' . $model->upload->extension;
                    if ($model->upload->saveAs($filePath)) {
                        $model->image = $filePath;
                    }
                }

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

and using it like this:

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $modelArtworks = $model->eventArtworks;
 
        $formArtworks = Yii::$app->request->post('EventArtwork', []);
        $this->handlePostSave($formArtworks);
 
        foreach ($formArtworks as $i => $formArtwork) {
            //other stuff
        }

And it returns: app\controllers\EventFormController::handlePostSave(): Argument #1 ($model) must be of type app\models\EventArtwork, array given, called in C:\Users\edgar\Projects\yii2-dynamic-tabular-form-app\controllers\EventFormController.php on line 135

Seems like I'm struggling with arrays.

What I have done already is in Gist. What I'm doing wrong?

Thank you,

Edgar

I expect to image(s)/file(s) be uploaded, saved in DB.

Upvotes: 0

Views: 64

Answers (1)

Evgeny
Evgeny

Reputation: 44

You send the values $formArtworks = Yii::$app->request->post('EventArtwork', []); to the handlePostSave function. although there will always be an array, and the handlePostSave function expects the EventArtwork model, because of this, the error

Worth doing it:

$this->handlePostSave($model->eventArtworks);

Upvotes: 0

Related Questions