Answer the question
In order to leave comments, you need to log in
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' => 'Имя']); ?>
...
$model->populateRelation('author', new Author());
Answer the question
In order to leave comments, you need to log in
> 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 questionAsk a Question
731 491 924 answers to any question