Need an example of dropDownList() and listData() working together

Hi,

I’ve been working for the past 2 hours to try to generate a simple drop down list in my view.

I am a beginner and not capable to get things working based on the document here. I am pretty lost about the data type and coudln’t figure out why we need listData() to generate data for dropDownList(). Learning how to use dropDownList() is hard enough for me.

Please help me provide an example, and assume I know nothing.

Thank you!

  • Nick

this is my code in view


<?php echo $searchForm->dropDownList($searchFormModel,$category, 'option1'); ?>

and having the following error


// Normal dropdownlist

<?php echo $form->dropDownList($model, 'field_name', array(1=>'test1', 2=>'test2'));?>




// List data need when populating dropdown from database values

<?php echo $form->dropDownList($model,'node_types_id', CHtml::listData(NodeTypes::model()->findAll(array('order' => 'name')),'id','name'));?>



Hi,

This page goes into some detail into how listData works:

http://www.yiiframework.com/wiki/48/by-example-chtml/

I assume based on the syntax you are using that you are using CActiveForm, the second parameter needs to be a valid attribute on your Model, so this is why you are getting an error. The third parameter needs to be an array.

Example:




$model = new MyModel();

$model->category_id = 1;


$categories = array(1 => 'Parts', 2 => 'Services');


<?php echo $searchForm->dropDownList($model, 'category_id', $categories); ?>




Or if you want categories from some model:




$model = new MyModel();

$model->category_id = 1;


<?php echo $searchForm->dropDownList($model, 'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>




So in the second case, listData takes the attributes named ‘id’ and ‘name’ on Category to use in the array to return.

Hope this helps you a bit.

Thank you very much!

I got this error,

Undefined variable: form

You might have not defined in php or you might not used $form in previous ,so the error arise you can use the below code to avoid this error.


echo CHtml::activeDropDownList($model, 'name', array('1'=>'One','2'=>'Two'),array('empty'=>'Select Option'));