I have two related models in hasToMany relation. The first is Invoices
and the second is InvoiceItems
. As a prototype process, I'm trying to conjugate the two models through the update
view of the InvoicesController
using the following code in actionUpdate
of InvoicesController
:
...
use common\models\Invoices;
use common\models\InvoicesSearch;
use common\models\InvoiceItems;
...
public function actionUpdate($id)
{
$model = $this->findModel($id);
$invoiceItems = new InvoiceItems();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$invoiceItems->invoice_id = $model->id;
if ($invoiceItems->load(Yii::$app->request->post()) && $invoiceItems->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
else{
// return false;
}
} else {
$invoiceItems->invoice_id = $model->id;
return $this->render('update', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]);
}
}
The following in update
view:
<div class="invoices-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]) ?>
</div>
Finally, the following in _form
view:
<div class="invoices-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'created')->textInput() ?>
<?= $form->field($model, 'type')->textInput(['maxlength' => true]) ?>
<hr />
<?= $form->field($invoiceItems, 'item_id')->textInput();?>
<?= $form->field($invoiceItems, 'unit_id')->textInput();?>
<?= $form->field($invoiceItems, 'qty')->textInput();?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The above code succeeded in saving data in invoice_items
table. However, the update view form has empty fields for InvoiceItems
model. i.e item_id
, unit_id
and qty
are empty in the update form after saving.
Notice: This is initial code, i.e I will work later to be able to add many items to the invoice, but now I just try to have one item related to the invoice.
Seems the update view is empty because you render and empty InvoceItmes ..
you render update view in else section and this section the value posted are not loaded
for populate the data for $invoceItems you need somethings like
Obviously this is for a single model.. you must refactory form more than one..