Easy to create dependent dropdown in yii framework

In “_form.php”

  1. <!–First Select Box–>
  2. <select class=“select” name=“SaleOrderProduct[product_category_id]“ id=“product_category_id”>
  3. <option value=“0″>- - - Select Product Category - - -</option>
  4. <option value=“1″>Item 1</option>
  5. <option value=“2″>Item 2</option>
  6. <option value=“3″>Item 3</option>                       
  7. </select>
  8.  
  9. <!–Second Select Box–>
  10. <select class=“select”  name=“SaleOrderProduct[product_id]“ id=“product_id”>
  11. </select>
  12.  
  13.  
  14. //create script for show product base on product category
  15. <script>
  16.     jQuery(“#product_category_id”).change(function(){
  17.         var category = jQuery(“#product_category_id”).val();
  18.         var dataString = ‘category=’+ category;
  19.         jQuery.ajax({  
  20.           type: “POST”,  
  21.           url: “<?php echo Yii::app()->request->baseUrl; ?>/index.php/saleOrder/getProduct”,
  22.           data: dataString,
  23.           success: function(data)
  24.           {
  25.               jQuery(“#product_id”).html(data);
  26.           }
  27.                });
  28.         
  29.     });
  30. </script>

 

In "SaleOrderController.php -> getProduct" here getProduct is a function.
  1. //this function use for get product name based on product category
  2.     public function actionGetProduct()
  3.     {
  4.         $categoryId = $_POST[category];
  5.         //select data from your database base on $categoryId variable
  6.         $product = ProductInfo::model()->findBySql(“select id, product_name from product_info where status=’ACTIVE’ and deleted=’0′ and company_id=’”.Yii::app()->user->companyId.“‘ and product_category_id=’”.$categoryId.“‘”);
  7.         echo “<option value=’0′>— Select a product —</option>”;
  8.         for($i=0; sizeof($product)>$i; $i++)
  9.         {
  10.             echo “<option value=’”.$product->id.“‘>”.$product->product_name.“</option>”;
  11.         }
  12.     }


			

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>