DropDown List populated from another model


I have a Model A and a Model B.

While Creating model B i want to save its type

Type can be known from the Model A.title which is nothing but different types defined already.

So in _form.php of B i want to show options populated from A’s rows in a dropdownlist.

What is the best way to populate the various titles out of table A…?

Should I add any function into model A’s code and call it from B’s form…?

Pls tell me with example or give me link for reference…!

-Big O


in your view you can use like


<?php echo $form->dropDownList($model,'item_type_id', CHtml::listData(ItemType::model()->findAll(), 'id', 'type'), array('empty'=>'select Type')); ?>

Thanks Marco,

That was helpful :)

-Big O

It helped me too.

What was missing was the listData to transform an array as the DropDownList wait …



I have a problem in this…

I have a table ‘professionals’. This contain the fields ‘id’, ‘name’, ‘orto’, ‘protetic’, ‘dentist’.

In other table: ‘clients’. I have ‘id_client’, ‘PROFESSIONAL’. This field contain the profecionals.id

In the _form of clients model, i need to populate a dropdownlist with all professionals that the field dentist value is 1

Your code return without criteria. Sometimes the last record… sometimes 2 last records…

Table professionals

                            id      name    mold   orto    prote    denist                                

                            1 	cris 	1 	1 	1 	1

                 	2 	lucas 	0 	1 	0 	1

                	3 	carol 	0 	0 	0 	1

                            4       marta   0       1       0       0


Select a type



The correct return is:

Select a type




Please, can you help me?

Thanks by your help!

i have the same problem too, returns me ids instead of name, surname etc…

Hi, from Marco W code, just add the condition and params in findAll()


echo $form->dropDownList(






array('empty'=>'Select Professional')); 


More information at http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAll-detail

Hope this helps!


Another way is to create a function to retrieve the data in the form of an array. In the model, let’s say we call it getAttribute(). It could be as simple as state abbreviations:



public function getAttribute()


 return array(





The user would see "Alabama", "AL" would be stored in the db. To retrieve an array out of the database use the most suitable find method for whatever model you need:

	public function getAttribute()


	  $customers = Customer::model()->findAll();

		$cust = array();

		foreach($customers as $c)


			$cust[$c->id] = $c->name;


		return $cust;


This would show customers names in the dropdown and store the id. You could substitute the attributes depending on what you want to display or store. Then in the _form view file:

<?php echo $form->dropDownList($model,'attribute', $model->getAttribute()); ?>