2013-05-08 164 views
1

我想從數據庫中獲取productTypes的列表,並將它們輸出到下拉列表中,然後將其用於ajax填充第二個下拉列表。Yii - 填充下拉列表

步驟1:控制器從數據庫中獲取productTypes 第2步:控制器的productTypes對象轉換爲一個列表 步驟3a:輸出列表鑑於 步驟3b來測試:填充下拉與列表視圖

片段控制器的

public function init() 
{ 

    $this->dynamicTypes(); 
    $this->render('calculator', array('types' => $this->_types)); 
} 


public function dynamicTypes() 
{ 
    $this->_types = CHtml::listData(ProductType::model()->findAll(), 'id', 'type'); 
} 

查看文件片段

<?php 
    // Step 3a (this works fine) 
    echo '<pre>'; 
     print_r($types); 
    echo '</pre>'; 

    // Step 3b - Returns an error 
    echo $form->dropDownList('productTypes',1, array($types)); 
?> 

<?php $this->endWidget(); ?> 

</div> 

隨着步驟3b中,我曾嘗試以下:

echo $form->dropDownList('productTypes',1, array($types)); 
Error Msg: get_class() expects parameter 1 to be object, string given 

根據http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail,DropDownList的方法採用以下參數:

public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ()) 

其中第一個參數是指示名稱的的輸入字段。

我做了什麼錯,我該如何解決這個問題?

UPDATE

echo CHtml::dropDownList('productTypes',1, array($types)); 

似乎工作,但是當我看到在視圖中的下拉列表中,由於某種原因,沒有在下拉列表0。出於某種原因,它是把選項到選項組

<select name="productTypes" id="productTypes"> 
<optgroup label="0"> 
<option value="1">Scrap</option> 
<option value="2">Coin</option> 
<option value="3">Bar</option> 
</optgroup> 
</select> 

解決: 刪除array($types),只有$types

echo CHtml::dropDownList('productTypes',1, $types); 
+0

你得到一個分組的下拉菜單,因爲你用'陣列($類型)',而不是僅僅'$ types'。 – 2013-05-08 14:25:00

回答

1

更換好像$formCActiveForm類的對象。此版本的dropDownList方法採用CModel類的實例。

看到這裏的方法簽名CActiveForm::dropDownList

使用

echo CHtml::dropDownList('productTypes',1, array($types)); 

,而不是

echo $form->dropDownList('productTypes',1, array($types));