(以下貼出的只是部分核心代碼;並不代表完整思路)
view.php
<?= $form->field($model,'level_one_id')->dropDownList([0=>'--請選擇一級分類--']+$model->getCategoryList(0),
[
'onchange'=>'
$(".form-group.field-enterprise-category_id").hide();
$.post("'.yii::$app->urlManager->createUrl('admin/enterprises/site').'?typeid=1&p_id="+$(this).val(),function(data){
$("select#enterprises-level_two_id").html(data);
});',
]) ?>
<?= $form->field($model, 'level_two_id')->dropDownList([0=>'--請選擇二級分類--']+$model->getCategoryList($model->level_one_id),
[
'onchange'=>'
$(".form-group.field-enterprise-category_id").show();
$.post("'.yii::$app->urlManager->createUrl('admin/enterprises/site').'?typeid=2&p_id="+$(this).val(),function(data){
$("select#enterprises-level_three_id").html(data);
});',
]) ?>
<?= $form->field($model, 'level_three_id')->dropDownList([0=>'--請選擇三級分類--']+$model->getCategoryList($model->level_two_id)) ?>
controller.php
/**
* 獲取商家分類信息
* @param $p_id
* @param int $typeid
*/
public function actionSite($p_id,$typeid=0){
$model = new Enterprises();
$model = $model->getCategoryList($p_id);
if($typeid == 1){$notice="--請選擇二級分類--";}else if($typeid == 2 && $model){$notice="--請選擇三級分類--";}
echo Html::tag('option',$notice, ['value'=>'0']) ;
foreach($model as $value=>$name)
{控制器中的site方法中用到了html::tag,請使用命名空間use yii\helpers\Html;否則無法正確輸出。
echo Html::tag('option',Html::encode($name),array('value'=>$value));
}
}
model.php
public function getCategoryList($p_id){
$model = EnterpriseCategory::find()->where('p_id=:p_id',[':p_id'=>$p_id])->all();
return ArrayHelper::map($model, 'id', 'p_name');
}
參考鏈接:http://www.yiichina.com/tutorial/468