Creating dropdown list from related table

I have 2 tables:


Primary Key: id


Foreign Key: category_id

What I am trying to do is populate the category_id field in a drop down list in a create form that pulls all the categories from the tbl_category table. I looked up the code for this and added the following code in the public function actionCreate() located in the content controller:

public function actionCreate()


	  $model=new Content;

	// retrieve the category model from db

       $categorymodel = Category::model()->findAll(

               array('order' => 'description'));


       // format list as $key=>$value with listData

       $categorylist = CHtml::listData($categorymodel, 

          'id', 'description');


In the view _form, I then reference the $categorylist as my key=>value pairs to populate the dropdown:

<?php echo CHtml::dropDownList('category_id', $select, $categorylist, array('empty' => '(Select a category'));?>	  

I am getting the following error when I try and access the form:

"Invalid argument supplied for foreach()"

Can someone tell me what I am doing wrong here. Are my naming conventions incorrect?

Any help would be appreciated.


I try to use CHtml::activeDropDownList when using listData.

*Not tested.

<?php echo CHtml::activeDropDownList($model,'field_name',CHtml::listData(Category::model()->findAll(array('order'=>'description')),'id','description'), array('empty' => '(Select a category'));?>


there might be two problems -

  1. $select is not assigned anything.

  2. you are not passing $categorylist in your render method in the controller

Maybe this e.g. will help -

If the above does not help, post the complete controller action code as well as the complete view code


Thanks for the help. Yes, it was the select not being assigned. In any case, I added the following function in the content model and it works perfectly:

  public function getCategories()


     //this function returns the list of categories to use in a dropdown	

      return CHtml::listData(Category::model()->findAll(), 'id', 'description');


in views>>content>>_form.php file:

<?php echo CHtml::activeDropDownList($model,'category_id', $model->getCategories(),array('prompt' => '(Select Category)')); ?>

Hello there im having a problem creating a dynamic drop down list, i’ve tried this method and it does create a drop down list but when submitting its giving an error that categories cannot be blank can someone help what am i getting wrong?