Question

I want to get a list of productTypes from the database and output them to a dropdownlist which will then be used to ajax populate a second dropdown list.

Step 1: Controller gets productTypes from database Step 2: Controller converts the productTypes object to a list Step 3a: Output list to test in view Step 3b: Populate a dropdown with the list view

Snippet of controller

public function init()
{

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


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

View File Snippet

<?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>

With step 3b, I have tried the following:

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

According to http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail, the dropDownList method takes the following arguments:

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

where the first argument is a string indicating the name of the input field.

What have I done wrong and how can I fix this?

UPDATE

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

seems to work, but when I look at the dropdown in the view, for some reason, there is a 0 in the dropdownlist. For some reason, it is putting the options into an optiongroup

<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>

SOLVED: Removed array($types), replaced with just $types

echo CHtml::dropDownList('productTypes',1, $types);
Was it helpful?

Solution

Seems like the $form is an object of the CActiveForm class. This version of the dropDownList method takes an instance of CModel class.

See the method signature here CActiveForm::dropDownList

Use

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

instead of

echo $form->dropDownList('productTypes',1, array($types));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top