Yii2:如何在一个视图中使用两个模型?

时间:2017-09-11 15:50:03

标签: php model-view-controller model yii2 yii2-advanced-app

我有一个名为 Person.php 的模型和一个名为 Country.php 的模型。 然后我有了 Persons / create.php

的观点

我包含了国家/地区的模型,我称之为 $ modelCountry ,但它无效。我收到了错误:

  

未定义的变量:modelCountry

这是 model / Persons.php 文件。

<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Person */
/* @var $modelCountry app\models\Country */

?>
<div class="person-create">

    <?php $form = ActiveForm::begin(); ?>
        <?= $form->field($model, 'phone')->textInput() ?>
        <?= $form->field($modelCountry, 'name')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create') ?>

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

</div>

然后我想使用发送按钮将两个模型发送到控制器(controllers / PersonsController.php)

2 个答案:

答案 0 :(得分:2)

似乎你想要在一个时间内输入两个不同的模型 为此你不需要在视图中包含第二个模型,但是在控制器中你应该为类创建模型..传递给createView并正确管理提交的值然后为最后渲染视图

<?php
    define("__HOST__", "localhost");
    define("__USER__", "root");
    define("__PASS__", "root");
    define("__BASE__", "db_blog");

    class DB {
        private $con = false;
        private $data = array();

        public function __construct() {
            $this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
            if(mysqli_connect_errno()) {
                die("DB connection failed:" . mysqli_connect_error());
            }
        }
        public function qryPop() {
            $sql = "SELECT * FROM `tb_blog` ORDER BY `id`" ;

            $qry = $this->con->query($sql); 
            if($qry->num_rows > 0) {
                while($row = $qry->fetch_object()) {
                    $this->data[] = $row;
                }
            } else {
                $this->data[] = null;
            }
            $this->con->close();
        }

?>

在渲染功能的动作视图中添加所需的模型

public function actionCreate()
{
    $model = new Person();
    $modelCountry = new Country()

    if ($model->load(Yii::$app->request->post('Person') &&  ($modelCoutr->load(Yii::$app->request->post('Country'))  {
        $model->save();
        $modelCountry->save();
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
            'modelCountry' => $modelCountry,
        ]);
    }
}

然后在你的视图中,您可以使用$ model for model和$ modelCountry来引用yourModelCountr

答案 1 :(得分:2)

您需要将变量modelCountry传递给视图文件

在您的控制器操作中:

    return $this->render('create', [
        'model' => $model,
        'modelCountry' => $modelCountry,
    ]);
相关问题