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']);
}
Instead of using
parent_idin 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.
Of course, you can implement such a functionality by yourself, but it's not that easy as it seems in the beginning.