我在hasToMany关系中有两个相关的模型。第一个是Invoices
,第二个是InvoiceItems
。作为原型流程,我尝试使用update
的{{1}}中的以下代码,通过InvoicesController
actionUpdate
视图将两个模型结合在一起:
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,
]);
}
}
视图中的以下内容:
update
最后,<div class="invoices-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]) ?>
</div>
视图中的以下内容:
_form
上面的代码成功地将数据保存在<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>
表中。 但,更新视图表单包含invoice_items
模型的空字段。保存后,更新表单中的InvoiceItems
,item_id
和unit_id
为空。
注意:这是初始代码,即我稍后会在发票中添加许多项目,但现在我只想尝试一个与发票相关的项目。
答案 0 :(得分:1)
似乎更新视图为空,因为您渲染并清空InvoceItmes ..
$invoiceItems = new InvoiceItems();
您在else部分中呈现更新视图,而此部分未发布已发布的值
$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 {//****** here the $invoceItems is empty (It has just been created) ***
//$invoiceItems->invoice_id = $model->id;
$invoceItems= findInvoceItmesModel($model->id);
return $this->render('update', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]);
}
用于填充$ invoceItems的数据,你需要像
这样的东西protected function findInvoiceItemsModel($id)
{
if (($model = InvociceItems::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
显然这是针对单个模型的..你必须重构一个以上的形式..