Pivot Table Relation Field Form

Pivot table relation

Anyone know how to present the checkboxList or any other widget in the update form, with the tags selected during the create article or post, already selected?

I believe this is something most of the people need.

Many thanks in advance.

It’s pretty simple.

First you create model attribute to hold these values, like this:


public $pivot_ids = [];

Then you fill it with pivot values


$record->pivot_ids = \yii\helpers\ArrayHelper::getColumn(

    $record->getPivot()->asArray()->all(),

    'pivot_id'

);



where ‘getPivot’ is a relation to pivot table.

Finally you create a checkbox list:


<?= $form->field($record, 'pivot_ids')->checkboxList($options]); ?>

where ‘options’ is a list of options. You can get it like this:


$list = YourModel::find()

    ->select(['id', 'name'])

    ->asArray()

    ->all();


$options = \yii\helpers\ArrayHelper::map($list, 'id', 'name');

Personally I like to store this in model,


public static function listData()

{

    $data = static::find()

        ->active()

        ->select(['id', 'name'])

        ->orderBy('weight DESC, name')

        ->asArray()

        ->all();


    return \yii\helpers\ArrayHelper::map($data, 'id', 'name');

}



and then use $options = MyModel::listData()

I have a curiosity in your code:


public static function listData()

{

    $data = static::find()

        ->active()

        ->select(['id', 'name'])

        ->orderBy('weight DESC, name')

        ->asArray()

        ->all();


    return \yii\helpers\ArrayHelper::map($data, 'id', 'name');

}

what is "->active()"?

Nothing special, just my custom named scope, something like ‘is_disabled = 0’.

I dont want to output the records that are still in ‘draft’ state, so created a scope for those.

Finally, I’ve got it. Thanks to you. Many thanks ORey. You are the best.

It’s a pity the documentation is so poor (for a while I hope)

I couldn’t reach it if there wasn’t a helpful member like you.

I think I will post a wiki with this simple relations solutions. Surely it will help a lot of people.

Many thanks once again.

As far as I know, there are two (!) books being written, so the docs are supposed to be awesome.