使用yii1在下拉列表中设置所选选项

时间:2016-07-15 06:14:53

标签: php yii

我是yii1的新手,遇到了问题。    我需要根据从其他页面传递的ID来选择我的下拉列表。

我的控制器

$cat = $_POST['mySelect'];
$post = file_get_contents("...................");   
$category = CJSON::decode($post, true);
$this->render('//Product/index', array('category'=>$category,'cat'=>$cat));

查看页面

<?php

echo CHtml::label('Category : ','cat'); 
                        $options = array();
                            foreach($category as $user) :

                                foreach($user as $use):

                                    $options[$use['id']] = $use['name'];
                                    if($options[$use['id']]== $cat){
                                        $sel='selected';
                                    }
                                endforeach;
                            endforeach;

                            echo CHtml::dropDownList('mySelect', 'name', $options,array('class'=>'selectpicker select_box','selected'=>$sel,'onchange'=>'select_bl(this.value)'));

?>

我没有数据库。

我不知道如何使用

 echo CHtml::dropDownList($cat, 'category',Html::listData(category::model()->findAll(), 'id', 'name'),$classification_levels_options);

任何人都可以帮我这个???

在我的代码中,$ cat是所选类别ID的ID,$ category是所有类别的列表。

2 个答案:

答案 0 :(得分:0)

// $ cat =您要选择的类别ID

echo CHtml :: dropDownList('category',$ cat,Html :: listData(category :: model() - &gt; findAll(),'id','name'));

答案 1 :(得分:0)

嗨,看看CHtml::dropDownList的语法是这个

dropDownList($name,$select,$data,$htmlOptions=array())

所以你的syntax应该是

<?php
 foreach($category as $user){
                                foreach($user as $use){

                                    $options[$use['id']] = $use['name'];
                                                                   }
                         }
    echo CHtml::dropDownList('category',$cat, $options);

我(根据您的问题)假设$optionsarray category你得到的$catkey的{​​{1}}值category

通常我们使用CHtml :: listdata来获取数组

如果您的模型为categories table,请假设model的名称为Category.php,那么您可以简单地使用findallCHtml::list }数据获得array

$options = CHtml::listData(Category::model()->findAll(), 'id', 'name'));

然后简单地使用//不需要使用foreach循环

echo CHtml::dropDownList('category',$cat, $options);