D
D
des1roer2016-01-18 07:32:19
Yii
des1roer, 2016-01-18 07:32:19

Yii 2 use 2 models in one controller?

I follow the example stackoverflow.com/questions/28567736/yii2-multiple...
two models - human and passport
controller

public function actionCreate()
{
    $human = new Human();
    $passport = new Passport;

    if ($human->load(Yii::$app->request->post()) && $passport->load(Yii::$app->request->post()) && Model::validateMultiple([$human, $passport]))
    {

        $human->save(false); // skip validation as model is already validated
        $passport->id = $human->passport_id; // no need for validation rule on user_id as you set it yourself
        $passport->save(false);

        return $this->redirect(['view', 'id' => $human->id]);
    }
    else
    {
        return $this->render('create', [
                    'human' => $human,
                    'passport' => $passport,
        ]);
    }

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

view
<?php

    use yii\helpers\Html;
    use yii\widgets\ActiveForm;
    use app\modules\proj\models\Passport;

    /* @var $this yii\web\View */
    /* @var $model app\modules\proj\models\Human */
    /* @var $form yii\widgets\ActiveForm */
    ?>

    <div class="human-form">

        <?php
        $form = ActiveForm::begin([
                    'id' => $human->isNewRecord ? 'human-form-create' : 'human-form-update',
        ]);
        ?>

        <?= $form->field($human, 'name')->textarea(['rows' => 6]) ?>

            <?= $form->field($human, 'passport_id')->textInput() ?>

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

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

    </div>

I get
Call to a member function formName() on a non-object

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2016-01-18
@evgenybuckharev

You have a connection between $human and $passport, why are you doing:
$passport->id = $human->passport_id;
$passport->save(false);
Call to a member function formName() on a non-object
This error indicates that you are trying to call the formName() method not on an object, but possibly on a string or array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question