Saving related data via activeform

I’m having trouble saving relational data, and I can’t find any best practice how to do it either. I have two models: Project and Person. Multiple persons can be attached to a project. So I created a relationship in the Project model via junction table ‘project_person’:

public function getPersons()


		return $this->hasMany(Person::className(), ['id' => 'person_id'])

			->viaTable('project_person', ['project_id' => 'id']);


In the _form.php view of the Project, I have a checkboxlist showing the persons that can be attached to a Project:

	<?= $form->field($model, 'persons')->checkboxList(ArrayHelper::map(Person::find()->all(), 'id', 'first_name')); ?>

This works. If I manually add a record to my junction table, a checkbox is even pre-checked too. However, I don’t understand how this information should be saved. Should it be done automatically by Yii?

I tried creating an afterSave method, to ‘manually’ update the rows in the junction table. While $this contains all the information of the model that is going to be saved, $this->persons doesn’t exist there.

You are close.

Examine your $_POST data. You should see an array of persons populated. What you need to do either in controller or in your model afterSave() is to load() the array of post data and loop through. The reason that it doesn’t exist is that you haven’t loaded it.