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.