J.K*_*.A. 2 php activerecord yii yii2
我有两个表:product和product_type(与模型相关的产品和Product_type):
product : product_id, product_type_id, name, etc...
product_type : product_type_id, name, desc, etc...
Run Code Online (Sandbox Code Playgroud)
两者都与关键"product_type_id"相关.
我使用gii crud生成器为两个表创建了crud.现在,在产品表单页面上,我想使用Yii ActiveRecord在下拉字段中显示所有product_type名称的列表.我在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);
?>
Run Code Online (Sandbox Code Playgroud)
但它显示空白下拉字段:(
我怎样才能做到这一点?
解决了我自己:)
只需提供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);
?>
Run Code Online (Sandbox Code Playgroud)
在Yii2中, CHtml类不再存在。
以下是基于以下假设的解决方案:
<?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)
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10731 次 |
| 最近记录: |