2013-09-21 242 views
0

我有一個下拉列表,當我想在另一個下拉列表中的某個項目被選中時填充。下拉列表都與從控制器傳遞的數據/模型綁定。並通過調用模型中的函數從數據庫填充第一個下拉列表。 Heres'的形式,Yii填充另一個下拉列表中的下拉列表

echo $form->dropDownListRow($modelunit, 
     'superunit', 
     $model->getSunits(), 
     array(
     'ajax' => array(
     'type'=>'POST', 
     'url'=>CController::createUrl('user/getunits'), 
     'update'=>'#unit_id', 
     ))); 

echo CHtml::dropDownList('unit_id','', array()); 

下面是由Ajax調用的用戶/ getunits操作。

$data=Unit::model()->findAll('sid=:sid', 
        array(':sid'=>(int) $_POST['superunit'])); 

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

我不斷收到錯誤「未定義指數:superunit」時,選擇第一個下拉。此外,您可能會注意到,我在第一個下拉列表中使用了form-> dropDownListRow,而在第二個列表中使用了CHtml :: dropDownList。這是因爲我對如何確切地使用ajax正確填充下拉列表以及正確綁定模型的語法毫無頭緒。

回答

3

您使用$form->dropDownListRow這就是爲什麼你會得到$_POST['MyModelName']['superunit']在你的服務器端

更改你的代碼像

$data=Unit::model()->findAll('sid=:sid', 
         array(':sid'=>(int) $_POST['MyModelName']['superunit'])); 

哪裏MyModelName是你使用一個模型)

或者像

echo CHtml::dropDownList('superunit'..... 

對於其他人 - this維基可能會提供幫助。

+0

謝謝。有效。 – redGREENblue

+0

抱歉再次打擾你。此代碼適用於創建。更新操作不起作用。我不斷收到錯誤「get_class()期望參數1是對象,數組given'.If我刪除下拉列表沒有錯誤。可能是什麼問題? – redGREENblue

+0

1.確保你有最新的Yii(從github抓取它)。 2.嘗試通過切換(打開/關閉)第二個下拉菜單進行調試。 3.嘗試通過遵循由Yii提供的堆棧跟蹤進行調試(挖掘框架代碼)。 4.嘗試提供Yii堆棧跟蹤的截圖。 – Pave