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

Comparing #11 with #12

Yii version

2.0

Content

[...]
### PostWithCategories model

And the last one is extended from Post. It has an additional attribute called 'category_ids' that will be used to handle the categories of the post. Note that **'category_ids' attribute is an array** of category ids.


```php

class PostWithCategories extends Post
{
[...]
We want to add a small utility method to Category model.


```php

class Category extends ActiveRecord
{
[...]
{
$categories = self::find()->order('name')->asArray()->all();
$items = ArrayHelper::map($categor
yies, 'id', 'name');
return $items;
}
[...]
### Create action


```php

/**
* Create Post with its categories
[...]
In the view script, we can use a listBox with multiple selection or a checkboxList to select the categories.


```php

<?php $form = ActiveForm::begin([
'id' => 'post-form',
[...]
It's almost the same with Create action:


```php

/**
* Update a post with its categories
[...]
It's different from create.php only in the text of the submit button:


```php

...
<?= Html::submitButton('Update', [
'class' => 'btn btn-primary'
]) ?>
...
[...]