0

I'm learning Yii2 by making a project.

I have two models: Company and CompanyFile. I'm using both of them in one form to create a Company, to upload related files and save them in associated table.

The problem is that the Company is being created but without uploading files and creating rows in associated table.

Here's the piece of Company Controller:

public function actionCreate()
{
    $model = new Company();
    $file = new CompanyFile();

    if ($model->load(Yii::$app->request->post()) && $file->load(Yii::$app->request->post())) {
        $model->save();
        $attachments = UploadedFile::getInstances($file, 'attachment[]');
        foreach($attachments as $a){
            if ($a->upload()){
                $file->company_id = $model->id;
                $file->attachment = $a;
                $file->save();
            }       
            else {
                return $this->render('create', [
                    'model' => $model,
                    'file' => $file,
                ]);
            }
        }
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
            'file' => $file,
        ]);
    }
}

Here's the piece of CompanyFile model:

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

Here's the views/company/_form.php:

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

<?= $form->field($model, 'name')->textarea(['rows' => 1, 'style' => 'width: 400px;']) ?>

<?= $form->field($file, 'attachment[]')->fileInput(['multiple' => true]) ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

After submitting form I'm redirected to newly created company page. No files uploaded. What may be wrong? I couldn't find any info about correct way of saving multiple files to another table in Yii2.

1 Answer 1

0

It needed to be

$attachments = UploadedFile::getInstances($file, 'attachment');

'attachment' without brackets.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.