N
N
NightBuster2015-11-24 14:16:42
Yii
NightBuster, 2015-11-24 14:16:42

Proper generation of ActiveForm from linked models in Yii2?

There was a problem, it is necessary to implement a form from related tables, let's conditionally call them Post and Author
I would like to find a Feng Shui solution that allows you to flexibly create forms using ActiveForm without adding a cloud of getters / setters to the models. One of the last attempts at this implementation was the following:

...
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model->author, 'LastName')->textInput(['placeholder' => 'Фамилия']); ?>
<?= $form->field($model->author, 'FirstName')->textInput(['placeholder' => 'Имя']); ?>
...

At the same time, I wrote the following in the actionCreate of the controller:
$model->populateRelation('author', new Author());
When saving the Post model, $this->author is empty
PS: I understand that this looks like a very stupid question for those who know how to do it right, but half a day of Google did not help me, unfortunately, to find normal working example, with listing of models, controller and form

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Khomenko, 2015-11-24
@NightBuster

> I would like to find a "feng shui" solution that allows you to flexibly create forms using ActiveForm without adding a cloud of getters / setters to the models.
Widget can be such a solution. It will take on the necessary cloud of getters / setters and allow you to reuse yourself in different places, if necessary.
> Post model sees $this->author empty when saving.
Are you confusing ->populateRelation($name, $records) with ->link($name, $model, $extraColumns = []) ?
UPD:
1. Create a form as in your example
2. After submitting the form, catch the data and load it into the model of the same class
$author= new Author();
$author->load( Yii::$app->getRequest()->post() );
3. You made sure that the data is correct, it passed the validation and save the model
$author->save();
4. Now you need to link Post and Author
# You can do it manually
$post->author_id = $author->id;
$post->save();
# Or automatically
$post->link( 'author', $autor );
5. That's it, the worker is complimentary. The entity is created and associated with the post.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question