Not able to Insert Record in Junction Table in Yii

I’ve three tables project, amenity and a junction table project_amenity, and here is the code:

Project Model:


<?php

namespace app\models;

use yii\db\ActiveRecord;


class Project extends \yii\db\ActiveRecord

{

    public function getAmenities()

    {

        return $this->hasMany(Amenity::className(), ['id' => 'amenity_id'])->viaTable('project_amenity', ['project_id' => 'id']);

    }


    public function rules()

    {

        return [

            [['name', 'city'], 'required'],

        ];

    }

}

Amenity Model:


<?php

namespace app\models;

use yii\db\ActiveRecord;


class Amenity extends \yii\db\ActiveRecord

{

    public function getProjects()

    {

        return $this->hasMany(Project::className(), ['id' => 'project_id'])->viaTable('project_amenity', ['amenity_id' => 'id']);

    }

}

ProjectController:


<?php


namespace app\controllers;


use Yii;

use yii\filters\AccessControl;

use yii\web\Controller;

use app\models\Project;

use app\models\Amenity;

use yii\helpers\ArrayHelper;

class ProjectController extends Controller

{

    public function actionCreate()

    {

        $project = new Project;

        $amenities = ArrayHelper::map(Amenity::find()->all(), 'id', 'name');


        if ($project->load(Yii::$app->request->post()) && $project->save()) {

            return $this->render(['confirm', 'id' => $project->id]);

        } else {

            return $this->render('create', [

                'project' => $project, 'amenities' => $amenities

            ]);

        }

    }

}

And here is the Incomplete create view:


<?php

use yii\helpers\Html;

use yii\widgets\LinkPager;

use yii\widgets\ActiveForm;


?>

<?php $form = ActiveForm::begin(); ?>

    <table class="table">

        <tr>

            <td><?= $form->field($project, 'name'); ?></td>

        </tr>

        <tr>

            <td ><?= $form->field($project, 'city'); ?></td>

        </tr>

        <tr>

            <td><?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?></td>

        </tr>

    </table>


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

I’am able to display the relational data but not able to insert. Please suggest how to display the amenity checkboxes on create view and and how to insert the data in project and project_amenity table from the create view.

Please take a look at the following wiki:

http://www.yiiframework.com/wiki/836/how-to-use-listbox-and-checkboxlist/

It only handles the relations of an existing model, but hopefully you can implement it in your create/update actions of the main model with some modification.

For example, you may add a new attribute called ‘amenity_ids’ to your Project model, and use it in place of the 4th model in the wiki article.

Added


public $amenity_ids = [];

in Project model.

And the view code:


<?= $form->field($project, 'amenity_ids')->checkboxList($amenities) ?>

But the code below in ProjectController not inserting data in junction table


foreach($project->amenity_ids as $amenity_id) {

                $project_amenity = new ProjectAmenity([

                    'project_id' => $project->id,

                    'amenity_id' => $amenity_id

                ]);

                $project_amenity->save();

            }

Did you place the code above after the saving of the project model? Otherwise its id could be null.

I’ve just revised the wiki.

How to create/update a model with its related items using Listbox or CheckboxList

Thanks after defining rules for $amenity_ids in Project modal it works.