0

I have a dropdown that I want to populate when an item in another dropdown is selected. Both the dropdown are tied to data/model passed on from controller. and the first dropdown is populated from DB by calling a function in the model. Heres' the form,

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());

Here's the action user/getunits called by Ajax.

$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);
    }

I keep getting an error "Undefined index: superunit" when first dropdown is selected. Also, you may notice I am using form->dropDownListRow for the first dropdown while using CHtml::dropDownList for the second. That's cause I am clueless on the syntax of how exactly to make sure the dropdown is populated correctly with ajax and at also properly bind to the model.

redGREENblue
  • 3,076
  • 8
  • 39
  • 57

1 Answers1

3

You use $form->dropDownListRow that's why you will get $_POST['MyModelName']['superunit'] on your server side

Change you code like

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

Where MyModelName is a model that you use)

Or like

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

For others - this wiki may help.

Pave
  • 2,347
  • 4
  • 21
  • 23
  • Sorry to bother you again. This code works fine for create. The update action doesn't work. I keep getting the error 'get_class() expects parameter 1 to be object, array given'.If i remove the dropdowns there's no error. What could be the issue? – redGREENblue Sep 22 '13 at 12:07
  • 1. Make sure you have the latest Yii (grab it from github). 2. Try to debug by toggling (on/off) the second dropdown. 3. Try to debug by following the stack trace provided by Yii (dig into framework code). 4. Try to provide a screenshot of Yii stack trace. – Pave Sep 22 '13 at 17:04
  • I guess the view code is fine and I got the reason why it is happening. The form is used to save inputs to multiple tables/models using relations. One of the relation is a HAS_MANY (1:N) which I guess is returning an array object when update form is being populated, hence the error. I am trying to find a solutions but failed so far. – redGREENblue Sep 22 '13 at 17:52