0

I have a model called Person.php and a model called Country.php. Then I have the view Persons/create.php

I included the model of the countries and I called $modelCountry but is it not working. I got the error:

Undefined variable: modelCountry

This is the model/Persons.php file.

<?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>

Then I want to use the send button to send both models to the controller (controllers/PersonsController.php)

Roby Sottini
  • 2,117
  • 6
  • 48
  • 88

2 Answers2

2

seems you want input two different model in a time
for this you don't need include the second model in view but in controller you should create models for both the class .. pass to the createView and properly manage the submitted values then for last render the view

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

In you action view in render function add the models you need

public function actionView($id)
{

    $yourModelCountry =  Country::find()->where(...)->one();

    return $this->render('view', [
        'model' => $this->findModel($id),
        'modelCountry' => $yourModelCountry , 
    ]);
}

then in your view you can refer both using $model for model and $modelCountry for yourModelCountr

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
2

You need to pass the variable modelCountry to your view files

In your controller action:

    return $this->render('create', [
        'model' => $model,
        'modelCountry' => $modelCountry,
    ]);
Imtiaz
  • 2,484
  • 2
  • 26
  • 32