I'm new with Yii2 framework, so. I have created 4 tables in my database and generated 4 models according to the tables. Now I need to create 1 form, which includes information of all 4 tables.
Fe Sale
table containts information of sale code
and Category
table contains information of category name
. I need to create a form in which I could enter all the information and it would store in a different tables according to the information.
Here is my SiteController action
:
public function actionCreate()
{
$category = new Category();
$sale = new Sale();
if ($category && $sale->load(Yii::$app->request->post())) {
if ($category && $sale->save()) {
return $this->redirect(['create']);
}
}
return $this->render('create', [
'category' => $category,
'sale' => $sale,
]);
}
And here is my Create
view:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $category app\models\Category */
/* @var $form ActiveForm */
?>
<div class="site-create">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($category, 'name') ?>
<?= $form->field($sale, 'code') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Submit'), ['class' => 'btn
btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
What I'm doing wrong? Thanks for any help
Change in SiteController action :
public function actionCreate()
{
$category = new Category();
$sale = new Sale();
// load request parameters for both category and sale model
if ($category->load(Yii::$app->request->post()) && $sale->load(Yii::$app->request->post())) {
if ($category->save() && $sale->save()) { // saving both model
return $this->redirect(['create']);
}
}
return $this->render('create', [
'category' => $category,
'sale' => $sale,
]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.