Method of Cascade Drop down Menu Realized by yii

  • 2021-07-10 18:57:16
  • OfStack

This article describes in detail the method of yii to implement cascading drop-down menus. The specific steps are as follows:

1. Add the following code to the template:


<?php
 echo $form->dropDownList($model, 'src_type_id', OrderSrc::options(), array(
 <span style="white-space:pre"> </span>'id' => 'task-order-src-id',
 ));
 echo $form->dropDownList($model, 'src_shop_id', array(''=>' All '), array(
 <span style="white-space:pre"> </span>'id' => 'task-shop-id',
 ))
?>

In this code, OrderSrc_options () reads a drop-down menu first. Call the options method in OrderScr model. The contents are as follows


public static function options($hasShop = true) {
 $model = new self();
 if($hasShop) $model->hasShop();
 $models = $model->findAll();
 $array = array(''=>' All ');
 foreach($models as $model) {
 $array[$model->src_id] = $model->src_name;
 }
 return $array;
}

2. Then add JS code in the template page to assign content to the second drop-down menu when the first drop-down menu changes.


<script type='text/javascript'>
$().ready(function(e) {
 $('#task-order-src-id').change(function(e) {
 refreshShops();
 });
 refreshShops();
 function refreshShops() {
 $.get('<?php echo $this->createUrl('getShops')?>', {
  'srcId': $('#task-order-src-id').val()
 }, function(html_content) {
  $('#task-shop-id')
  .html(html_content)
  .find('option[value=<?php echo $model->src_shop_id?>]')
   .attr('selected', 'selected');
 });
 }
});
</script>

In this section of JS code, the implementation calls a program to get the value of the second drop-down menu (call the actionGetShops method in Controller), any append to the second drop-down menu.

The actionGetShops method in Controller is as follows:


public function actionGetShops() {
 $srcId = $_GET['srcId'];
 $array = ThirdpartInterfaceConfig::options($srcId);
 $htmlContent = "<option value=''> All </options>";
 foreach($array as $k=>$v) {
 $htmlContent .= "<option value='{$k}'>{$v}</option>";
 }
 echo $htmlContent;
}

Related articles: