how to generating a dropdown list in yii2

2019-09-07 02:40发布

I tried to make a dropdown list in yii2 using this link : How to make a drop down list in yii2?

my code is :

<?php use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?= $listdata=ArrayHelper::map(Product::find()->all(),'id','name'); ?>
<?= $form->field($model, 'parent_id')-> dropDownList($listdata);  ?>

but I have a problem in line of using ArrayHelper
the problem is: PHP Notice – yii\base\ErrorException Array to string conversion.......! I tested the below code :

 $listData=ArrayHelper::map(Product::find()->asArray()->all(),'id','name');     

but it dos not solved and has the same error!

whats the problem? can somebody help me?

标签: yii
2条回答
Lonely孤独者°
2楼-- · 2019-09-07 03:12

You are trying to echo an array, change <?= to <?php in:

<?= $listdata=ArrayHelper::map(Product::find()->all(),'id','name'); ?>
查看更多
我命由我不由天
3楼-- · 2019-09-07 03:12

Try like this

   <?php
     use yii\helpers\ArrayHelper;
     use app\models\Product;
    ?>

   <?= $form->field($model, 'parent_id')->dropDownList(
        ArrayHelper::map(Product::find()->all(),'id','name'),
        ['prompt'=>'Select ']) 
    ?>
查看更多
登录 后发表回答