如何修复“;未定义的变量“;Yii2视图中出现错误


How to fix the "Undefined variable" error in Yii2 view?

这是我的控制器:

class RoomController extends Controller
{
public function actionCreate()
{
$model = new Room();
$modelSave = false;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
}
return $this->render('create', ['model' => $model,'modelSaved' => $modelSave]);
}
}

这是我的观点

<?php if($modelSave) { ?>
<div class = "alert alert-success" >
Model ready to be saved!
</div>
<?php } ?>
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class = "col-lg-12">
<h1>Room Form</h1>
<?= $form->field($model,'floor')->textinput()?>
<?= $form->field($model,'room_number')->textinput() ?>
<?= $form->field($model,'has_conditioner')->checkbox() ?>
<?= $form->field($model,'has_tv')->checkbox() ?>
<?= $form->field($model,'has_phone')->checkbox() ?>
<?= $form->field($model,'available_form')->textinput() ?>
<?= $form->field($model,'price_per_day')->textinput() ?>
<?= $form->field($model,'description')->textarea() ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('create',['class'=>'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>

当我检查它是否工作时,ErrorException显示:

PHP通知–yii''base''ErrorException未定义的变量:modelSave

我试过调试,但我不知道为什么$modelSave不能发送到视图";创建";。

您测试

<?php if($modelSave) { ?>

但是在你的渲染中你有

return $this->render('create', ['model' => $model,'modelSaved' => $modelSave]);

使用

<?php if($modelSaved) { ?>

您不按变量名称调用变量,您应该尝试检查$modelSaved,因为这是您给它的名称

更换

<?php if($modelSave) { ?>

通过

<?php if($modelSaved) { ?>