在Yii中生成动态下拉列表?

时间:2014-04-14 08:38:26

标签: php yii

我需要根据第一个选择生成第二个下拉列表。

在_form.php中查看:

<?php 
echo CHtml::dropDownList('category_id','', Category::allCategory(),
     array(
     'ajax' => array(
     'type'=>'POST', //request type
     'url'=>CController::createUrl('subcategory/dynamicSubCategories'), //url to call.
     //Style: CController::createUrl('currentController/methodToCall')
     'update'=>'#subcategory_id', //selector to update
     //'data'=>'js:javascript statement'
     //leave out the data key to pass all form values through
     )));

     //empty since it will be filled by the other dropdown
     echo CHtml::dropDownList('subcategory_id','', array());
?>

我也创建了控制器: 的 SubcategoryController.php

public function actionDynamicSubCategories() {
        $data = Subcategory::model()->findAll('category_id=:category_id', 
                array(':category_id' => (int)$_POST['category_id']));

        $data = CHtml::listData($data, 'id', 'title');
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

我在同一个控制器中注册了此动作的执行规则: function accessRules

array('allow', // deny all users
            'actions' => array('DynamicSubCategories'),
            'users' => array('@'),
        ),

表格类别&#39;具有结构: id,title,position 和Category :: allCategory()返回:

return CHtml::listData($models, 'id', 'title');

表&#39;子类别&#39;具有结构: id,title,category_id

不幸的是,调查是在第二个下拉列表中进行的,但没有显示任何内容,提示我输入不正确?

结果: Dropdownlist's

2 个答案:

答案 0 :(得分:0)

查看http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail,其中没有ajax params,只有HTMLOptions。您必须对ajax的更改事件{<1}}进行整理:

像那样:

select#category_id

答案 1 :(得分:0)

解决

<强> _form.php这个

<?php 
    echo $form->labelEx($model,'category_id');
    echo CHtml::dropDownList('category_id','', Category::allCategory(),
         array(
         'ajax' => array(
         'type'=>'POST', //request type
         'url'=>CController::createUrl('subcategory/dynamicSubCategories'), //url to call.
         //Style: CController::createUrl('currentController/methodToCall')
         'update'=>'#subcategory_id', //selector to update
         //'data'=>'js:javascript statement'
         //leave out the data key to pass all form values through
         )));
    echo $form->error($model,'category_id'); 

     echo $form->labelEx($model,'subcategory_id');
     echo CHtml::dropDownList('subcategory_id','', array());
     echo $form->error($model,'subcategory_id');
?>

<强> SubcategoryController.php

public function actionDynamicSubCategories() {
    echo $_POST['ajax'];
    $data = Subcategory::model()->findAllByAttributes(array('category_id' => $_POST['category_id']));

    $data = CHtml::listData($data, 'id', 'title');
    foreach ($data as $value => $name) {
        echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
    }
}