Eduardo
Eduardo

Reputation: 1831

Yii2. How to handle a checkbox array

I have 2 tables items and categories. In the items form I need to list all categories so user check more than one category. So far I am listing categories like this:

foreach($items as $item) {
            $modelCategory->itemCategoryId = $item->id;
            echo $form->field($modelCategory, 'itemCategoryId')
             ->checkbox([
                        'value' => $item->id, 
                        'label' => ''])
             ->label($item->name);
}

But first problem is the name of the field, how can I convert it into array?

I am thinking in adding a virtual attribute to my Item called "categories", and then use checkBoxList, any other way?

Upvotes: 0

Views: 1791

Answers (1)

Eduardo
Eduardo

Reputation: 1831

I have solved with checkboxList!!

$items = $this->_getList();
$selectedItems = $this->_getSelected();

echo  $form->field($this->modelForm, 'itemCategories')->checkboxList($items, $selectedItems);

Thanks!!!

Upvotes: 1

Related Questions