Yii2基本显示从另一个模型创建到另一个模型的视图

时间:2017-12-22 08:03:24

标签: php yii2 yii2-basic-app

我创建了一个名为Channel和CRUD Post的CRUD,所以我想将create Post表单添加到Channel的DetailView中;例如,当用户在Alpha详细信息下查看Channel Alpha时,他有来自Post的表单以在该Channel中创建帖子

用户可以查看频道的详细信息,也可以将Post添加到该频道

类似于:

通道控制器中的

public function actionView($id)
    {
        $ly_addPost = new Posts();
        return $this->render('view', [
            'model' => $this->findModel($id),
            'addpost' => $ly_addPost,
        ]);
    }

并在频道视图中我将其编辑为:

// Yii2代码

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Channel */

$this->title = $model->Channel_name;
$this->params['breadcrumbs'][] = ['label' => 'Channels', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="channel-view">

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

    <p>
        <?= Html::a('Update', ['update', 'id' => $model->Channel_id], ['class' => 'btn btn-primary']) ?>
        <?= Html::a('Delete', ['delete', 'id' => $model->Channel_id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ]) ?>
    </p>
    <div class="col-md-12">
        <?= $this->render ('_form', [
            'addpost' => $ly_addPost,
        ])
        ?>

        <div class="posts-form">

            <?php $form = ActiveForm::begin(); ?>

            <?= $form->field($model, 'Posts_title')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'Posts_text')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'Posts_file')->textInput(['maxlength' => true]) ?>

            <?php //= $form->field($model, 'Posts_crdate')->textInput() ?>

            <?= $form->field($model, 'Channel_id')->textInput(['maxlength' => true]) ?>

            <?= $form->field($model, 'Permissions_id')->textInput() ?>

            <?php //= $form->field($model, 'user_id')->textInput() ?>

            <div class="form-group">
                <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
            </div>

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

        </div>
    </div>

</div>

但我收到错误:

PHP注意 - yii \ base \ ErrorException

未定义的变量:ly_addPost

2 个答案:

答案 0 :(得分:1)

addpost更改为ly_addPost,如下所示

public function actionView($id)
{
    $ly_addPost = new Posts();
    return $this->render('view', [
        'model' => $this->findModel($id),
        'ly_addPost' => $ly_addPost,
    ]);
}

答案 1 :(得分:1)

只需在视图文件

中将$ly_addPost更改为$addpost即可
<div class="col-md-12">
        <?= $this->render ('_form', [
            'addpost' => $addpost,
        ])
        ?>
...