Search code examples
phpyiiyii2

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


Here is my controller:

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]);
}
}

and here is my view

<?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(); ?>

when i checked whether if it working, the ErrorException shows:

PHP Notice – yii\base\ErrorException Undefined variable: modelSave

I've tried to debug, but I have no idea why the $modelSave can't send to the view "create".


Solution

  • You test

    <?php if($modelSave) { ?>
    

    but in your render you have

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

    use

    <?php if($modelSaved) { ?>