Yii 2 множественные модели в одном экшене

1. В контролере подключить обе модели

2. Поменять действия контролера

3. Подключить атрибуты в view\create

4. В _form можно использовать строки из обеих таблиц

1. Контролер

<?php

namespace app\modules\proj\controllers;

use Yii;
use app\modules\proj\models\Human;
use app\modules\proj\models\HumanSearch;
use app\modules\proj\models\Passport;
use app\modules\proj\models\PassportSearch;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * HumanController implements the CRUD actions for Human model.
 */
class HumanController extends Controller
{

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Human models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new HumanSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Human model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Human model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $human = new Human;
        $passport = new Passport;
        $passport->issued = date('Y-m-d');

        if ($human->load(Yii::$app->request->post()) && $passport->load(Yii::$app->request->post()) && Model::validateMultiple([$human, $passport]))
        {
            $passport->save(false);
            $human->passport_id = $passport->id; // no need for validation rule on user_id as you set it yourself
            $human->save(false); // skip validation as model is already validated
            return $this->redirect(['view', 'id' => $human->id]);
        }

        return $this->render('create', [
                    'human' => $human,
                    'passport' => $passport,
        ]);
    }

    /**
     * Updates an existing Human model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $human = Human::findOne($id);
        $passport = Passport::findOne($human->passport_id);

        if ($human->load(Yii::$app->request->post()) && $passport->load(Yii::$app->request->post()) && Model::validateMultiple([$human, $passport]))
        {
            $passport->save(false);
            $human->save(false); // skip validation as model is already validated

            return $this->redirect(['view', 'id' => $human->id]);
        }

        return $this->render('update', [
                    'human' => $human,
                    'passport' => $passport,
        ]);
    }

    /**
     * Deletes an existing Human model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $id_ = Human::findOne($id)->passport_id;
        Human::findOne($id)->delete();
        Passport::findOne($id_)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Human model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Human the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Human::findOne($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

} 
 
2. views/create
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\modules\proj\models\Human */

$this->title = 'Create Human';
$this->params['breadcrumbs'][] = ['label' => 'Humans', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="human-create">

    <h1><?= Html::encode($this->title) ?></h1>

    <?=
    $this->render('_form', [
        'human' => $human,
        'passport' => $passport,
    ])
    ?>

</div>

3. _form

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\jui\DatePicker;

/* @var $this yii\web\View */
/* @var $model app\modules\proj\models\Human */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="human-form">

    <?php
    $form = ActiveForm::begin([
                'id' => $human->isNewRecord ? 'human-form-create' : 'human-form-update',
    ]);
    ?>

    <?= $form->field($human, 'name')->textInput() ?>
    <?= $form->field($passport, 'num')->textInput() ?> 
    <p><b>выдан</b></p>
    <?=
    DatePicker::widget([
        'model' => $passport,
        'attribute' => 'issued',
        'language' => 'ru',
        'dateFormat' => 'yyyy-MM-dd',
        'options' => ['class' => 'form-control'],
    ]);
    ?>
    <br/>
    <div class="form-group">
        <?= Html::submitButton($human->isNewRecord ? 'Create' : 'Update', ['class' => $human->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

4. index

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\proj\models\HumanSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Humans';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="human-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Human', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?=
    GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'name:ntext',
            'passport.num',
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]);
    ?>

</div>




Комментарии

Популярные сообщения из этого блога

Пишем логи на C# (.NET). Легкий способ.

Учебник yii2