Question

I have two tables: product and product_type (related to the models resp. Product and Product_type):

product : product_id, product_type_id, name, etc...
product_type : product_type_id, name, desc, etc...

Both are related with key "product_type_id".

I have created the crud for both tables using gii crud generator. Now on Product form page I want to display the listing of all product_type name in dropdown field using Yii ActiveRecord. I have added this line in views/product/_form.php script:

<?php
    $list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'id', 'id');
    echo $form->dropDownList($model, 'product_type_id', $list);
?>

But it's showing blank dropdown field :(

How can I do this?

Was it helpful?

Solution

Solved MySelf :)

By just providing product_type_name.

<?php
        $list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'product_type_id', 'product_type_name');
        echo $form->dropDownList($model, 'product_type_id', $list);
        ?>

OTHER TIPS

In Yii2 the class CHtml does not exist anymore.

Below is a solution, based on the following assumptions:

  • The Yii2 framework is used;
  • The table product_type is associated with the model Product_type;
  • The product_type table has a field called "type-name".


     <?php
         // get all product types from the corresponding table:
         $productTypes = Product_type::find()->orderBy('type-name')->asArray()->all(); 
         // create an array of pairs ('id', 'type-name'):
         $productTypeList = ArrayHelper::map($productTypes, 'id', 'type-name'); 
         // finally create the drop-down list:
         $form->field($model, 'product_type_id')->dropDownList($productTypeList) 
     ?>

Change your code like bellow

    <?php
    $list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'table_col_name1', 'table_col_name2'); //table_col_name1 is value of option, table_col_name2 is label of option
    // echo $form->dropDownList($model, 'product_type_id', $list);
    echo CHtml::dropDownList('name_of_the_dropdown', $model, $list);
    ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top