SELECT element on a foreign key

Hello everybody!

i’m a new YII user totally in love with this framework… congrats to the people who developed such a powerful tool!

i’ve been looking for an answer to this question for some days and couldn’t find one. Surprisingly, for it should be quite a normal thing. anyhow, here it comes:

I have a table BRAND with fields ID (INT NOT NULL AUTO_INCREMENT) and NAME. Then i have a table PRODUCT with fields ID (INT NOT NULL AUTO_INCREMENT), BRAND_ID (FOREIGN KEY that connects to BRAND->ID), NAME.

I did CRUD for both tables and they work, also the connections between tables (if i insert as PRODUCT->BRAND_ID a value that doesn’t exist, i get an error). But i’d like to put in the form for inserting PRODUCT entries a SELECT html element that allows me to select a BRAND->NAME and inserts the right BRAND->ID in PRODUCT->BRAND_ID field.

How can i achieve this?

thanks a lot for helping me! :)

You can do that with CHtml::dropDownList like this:




// Don't need to have criteria, but it's nice for more fine grained control

$criteria=new CDbCriteria;

$criteria->order='name';


$brands=CHtml::listData(Brand::model()->findAll($criteria),'id','name');


echo CHtml::dropDownList(

    'Product[brand_id]',

    $model->brand_id,

    $brands,

    array('empty' => '(No Brand)')

);

thanks a lot!! :)

i have to put this code in _form.php of views/product, right?

Hi,

Yes.

But i would suggest to use activeDropDownList instead of dropDownList:


echo CHtml::activeDropDownList(

     $model,    

    'brand_id',

    $brands,

    array('empty' => '(No Brand)')

);

regards

Ah yes… use that. Additionally in the new form model (1.1.1) there is also:


echo $form->dropDownList(

     $model,    

    'brand_id',

    $brands,

    array('empty' => '(No Brand)')

);