I have a product list where i need to enter new products. each product has a category and a subcategory.
everytime a new product is to be entered in the database, the category and the sub category to which it belongs is to be selected using dropdowns. i am able to populate the category dropdown but not the subcategory dropdown as it has to populate based on the category selected.
tables in the database
1)products–>product_id,product_name,cat_id,subcat_id
2)products_category–>cat_id,cat_name
3)products_subcategory–>subcat_id,subcat_name
here i present the code in _form.php
<?php echo $form->labelEx($model,'cat_id'); ?>
<?php$productCategoriesArray = CHtml::listData(ProductsCategory::model()->findAll(),'cat_id','cat_name');
echo $form->DropDownList($model,'cat_id',$productCategoriesArray,
array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('ProductsSubcategory/dynamicSubcategory'),
'update'=>'#subcat_id')));
ay;
?>
<?php echo $form->error($model,'cat_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subcat_id'); ?>
<?php
echo $form->dropDownList($model,'subcat_id',array());
?>
<?php echo $form->error($model,'subcat_id'); ?>
</div>
and here’s the code in the controller:
public function actionDynamicsubcategory()
{
$data=ProductsSubcategory::model()->findAll('cat_id=:parent_id',
array(':parent_id'=>(int) $_POST['cat_id']));
$data=CHtml::listData($data,'subcat_id','subcat_name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}