I’m taking the plunge to Yii2 and it has been a rather difficult one. I have been failing…miserably…even with super simple things like two models in one form.
How do you use multiple models in one form?
I keep getting an error:[size="2"] Call to a member function formName() on null[/size]
[i]UPDATE:
This error was because i wasn’t including the second model in the create.php and passing it to the render _form.php.[/i] i.e.
<?=
$this->render('_form', [
'model' => $model,
'FooBarModel' => $FooBarModel
])
?>
My controller
public function actionCreate() {
$model = new Foo();
$FooBarModel = new FooBar();
if ($model->load(Yii::$app->request->post()) && $FooBarModel->load(Yii::$app->request->post()) && Model::validateMultiple([$model, $FooBarModel])) {
$model->save(false); // skip validation as model is already validated
$FooBarModel->event_id = $model->id;
$FooBarModel->test_id = $FooBarModel->name;
$FooBarModel->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'FooBarModel' => $FooBarModel,
]);
}
}
My Form
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 155]) ?>
<?= $form->field($model, 'location_id')->dropDownList(ArrayHelper::map(Locations::find()->all(), 'id', 'name')); ?>
<?= $form->field($foobar, 'name')->dropDownList(ArrayHelper::map(Test::find()->all(), 'id', 'name')); ?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
[i]UPDATE:
You will also need to include the base model for validation of multiple models in your controller.
use yii\base\Model;
The code above does seem to be working. I updated the things that needed to be changes so other people can benefit from my mistakes!
[/i]