【问题标题】:Creating dropdown list from related table yii从相关表 yii 创建下拉列表
【发布时间】:2013-07-06 06:24:11
【问题描述】:

我有两个表:productproduct_type(分别与模型相关 Product 和 Product_type):

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

两者都与键“product_type_id”相关。

我已经使用 gii crud 生成器为两个表创建了 crud。现在在产品表单页面上,我想使用 Yii ActiveRecord 在下拉字段中显示所有产品类型名称的列表。我在 views/product/_form.php 脚本中添加了这一行:

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

但它显示空白下拉字段:(

我该怎么做?

【问题讨论】:

    标签: php activerecord yii yii2


    【解决方案1】:

    解决了我的自我:)

    只需提供 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);
            ?>
    

    【讨论】:

    • 我使用了这个解决方案,它可以工作。但是如果 product_type_id 为 null,那么它将显示 product_type_name 的第一项。是否可以只显示一个空白?
    【解决方案2】:

    Yii2 中,CHtml 类不再存在。

    以下是基于以下假设的解决方案:

    • 使用Yii2框架;
    • product_type与模型Product_type相关联;
    • product_type 表有一个名为“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) 
         ?>
    

    【讨论】:

      【解决方案3】:

      像下面这样更改你的代码

          <?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);
          ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-25
        • 2018-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多