1

I want to make a multiple category dropdown in product form yii2. The table category has a parent_id column. So when I want to choose the category with parent_id 0 or 1 it shows other categories with that parent_id. I use gii generator. Can you help me make controller model view it? controller

public function actionCreate()
{
    $model = new Product();
    $category = new Category();
    $time = time();
    $model->created_at = $time;
    $model->updated_at = $time;
    $dataCat = $category->getCategoryParent();
    if(empty($dataCat)){
        $dataCat = array();
    }

view

<?= $form->field($model, 'category_id')->dropDownList($dataCat,['prompt'=>'--obat--']) ?>

model

public function getCategoryParent()
{
    return $this->hasOne(Category::className(), ['idCate' => 'category_id']);
}
Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
Ice
  • 21
  • 3

1 Answers1

1

Instead of using parent_id in your category structure, I advice you to use nested-sets model, as you will face some technical limitations (like recursive query in SQL) and performance issues in the future.

There is a good tree-manager extension developed by Krajee, that allows you to embed a good looking drop-down (support multiple) for category selection. It has a good tree constructor in it as well.

tree-view input

Of course, you can implement such a functionality by yourself, but it's not that easy as it seems in the beginning.

Yerke
  • 2,187
  • 3
  • 19
  • 33