php 如何在yii2中制作下拉列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21569053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:15:41  来源:igfitidea点击:

How to make a drop down list in yii2?

phpdrop-down-menuyii2

提问by Dency G B

How to make a dropdownin yii2using an activeformand a model? Since all the methods has changed in yii2,how it is done in the new one?

如何dropdownyii2使用activeform和模型中创建一个?既然所有的方法都改变了yii2,那么在新的方法中是怎么做的呢?

回答by Dency G B

It is like

它像是

<?php
use yii\helpers\ArrayHelper;
use backend\models\Standard;
?>

<?= Html::activeDropDownList($model, 's_id',
      ArrayHelper::map(Standard::find()->all(), 's_id', 'name')) ?>

ArrayHelper in Yii2 replaces the CHtml list data in Yii 1.1.[Please load array data from your controller]

Yii2 中的 ArrayHelper 替换了 Yii 1.1 中的 CHtml 列表数据。 [请从您的控制器加载数组数据]

EDIT

编辑

Load data from your controller.

从控制器加载数据。

Controller

控制器

$items = ArrayHelper::map(Standard::find()->all(), 's_id', 'name');
...
return $this->render('your_view',['model'=>$model, 'items'=>$items]);

In View

在视图中

<?= Html::activeDropDownList($model, 's_id',$items) ?>

回答by ippi

It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.

似乎您已经找到了答案,但既然您提到了活动形式,我将再贡献一个,即使它只是略有不同。

<?php
    $form = ActiveForm::begin();

    echo $form->field($model, 'attribute')
        ->dropDownList(
            $items,           // Flat array ('id'=>'label')
            ['prompt'=>'']    // options
        );

    ActiveForm::end();
?>

回答by johnsnails

There are some good solutions above, and mine is just a combination of two (I came here looking for a solution).

上面有一些很好的解决方案,我的只是两个的组合(我来这里是为了寻找解决方案)。

@Sarvar Nishonboyev's solution is good because it maintains the creation of the form input label and help-block for error messages.

@Sarvar Nishonboyev 的解决方案很好,因为它维护了表单输入标签和错误消息帮助块的创建。

I went with:

我去了:

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

Again, full credit to: @Sarvar Nishonboyev's and @ippi

再次,完全归功于:@Sarvar Nishonboyev's 和 @ippi

回答by Midhun

It Seems there are many good answers for this question .So i will try to give a detailed answer

这个问题好像有很多很好的答案,所以我会尽量给出详细的答案

active form and hardcoded data

活动形式和硬编码数据

<?php
    echo $form->field($model, 'name')->dropDownList(['1' => 'Yes', '0' => 'No'],['prompt'=>'Select Option']);
?>

or

或者

<?php
    $a= ['1' => 'Yes', '0' => 'No'];
    echo $form->field($model, 'name')->dropDownList($a,['prompt'=>'Select Option']);
?>

active form and data from a db table

来自数据库表的活动表单和数据

we are going to use ArrayHelper so first add it to the name space by

我们将使用 ArrayHelper 所以首先将它添加到名称空间

<?php
    use yii\helpers\ArrayHelper;
?>

ArrayHelper has many use full functions which could be used to process arrays map () is the one we are going to use here this function help to make a map ( of key-value pairs) from a multidimensional array or an array of objects.

ArrayHelper 有许多可用于处理数组的完整函数 map () 是我们将在此处使用的函数,此函数有助于从多维数组或对象数组制作映射(键值对)。

<?php
    echo $form->field($model, 'name')->dropDownList(ArrayHelper::map(User::find()->all(),'id','username'),['prompt'=>'Select User']);
?>

not part of a active form

不是活动形式的一部分

<?php
    echo Html::activeDropDownList($model, 'filed_name',['1' => 'Yes', '0' => 'No']) ;
?>

or

或者

<?php
    $a= ['1' => 'Yes', '0' => 'No'];
    echo Html::activeDropDownList($model, 'filed_name',$a) ;
?>

not an active form but data from a db table

不是活动形式,而是来自数据库表的数据

<?php
    echo Html::activeDropDownList($model, 'filed_name',ArrayHelper::map(User::find()->all(),'id','username'),['prompt'=>'Select User']);
?>

回答by Sarvar Nishonboev

Have a look this:

看看这个:

use yii\helpers\ArrayHelper; // load classes
use app\models\Course;
    .....
$dataList=ArrayHelper::map(Course::find()->asArray()->all(), 'id', 'name');
<?=$form->field($model, 'center_id')->dropDownList($dataList, 
         ['prompt'=>'-Choose a Course-']) ?>

回答by DespeiL

Maybe I'm wrong but I think that SQL query from view is a bad idea

也许我错了,但我认为从视图中进行 SQL 查询是个坏主意

This is my way

这是我的方式

In controller

在控制器中

$model = new SomeModel();
$items=ArrayHelper::map(TableName::find()->all(),'id','name');


return $this->render('view',['model'=>$model, 'items'=>$items])

And in View

在视图中

<?= Html::activeDropDownList($model, 'item_id',$items) ?>

Or using ActiveForm

或者使用 ActiveForm

<?php $form = ActiveForm::begin(); ?>
 <?= $form->field($model, 'item_id')->dropDownList($items) ?>
<?php ActiveForm::end(); ?>

回答by Kalai S

<?= $form->field($model, 'attribute_name')->dropDownList(
         ArrayHelper::map(Table_name::find()->all(),'id','field_name'),
        ['prompt' => 'Select']
) ?>

This will help you...Don't forget to use the class file in header.

这将帮助您...不要忘记在标题中使用类文件。

回答by Bhola Singh

In ActiveFormjust use:

ActiveForm刚刚使用:

<?=
    $form->field($model, 'state_id')
         ->dropDownList(['prompt' => '---- Select State ----'])
         ->label('State')
?>

回答by Joe Miller

This is about generating data, and so is more properly done from the model. Imagine if you ever wanted to change the way data is displayed in the drop-down box, say add a surname or something. You'd have to find every drop-down box and change the arrayHelper. I use a function in my models to return the data for a dropdown, so I don't have to repeat code in views. It also has the advantage that I can specify filter here and have them apply to every dropdown created from this model;

这是关于生成数据,因此更适合从模型中完成。想象一下,如果您想更改下拉框中数据的显示方式,例如添加姓氏或其他内容。您必须找到每个下拉框并更改arrayHelper. 我在我的模型中使用一个函数来返回下拉列表的数据,所以我不必在视图中重复代码。它还具有我可以在此处指定过滤器并将它们应用于从此模型创建的每个下拉列表的优点;

/* Model Standard.php */

public function getDropdown(){
      return ArrayHelper::map(self::find()->all(), 's_id', 'name'));
}

You can use this in your view file like this;

您可以像这样在视图文件中使用它;

echo $form->field($model, 'attribute')
        ->dropDownList(
            $model->dropDown
        );

回答by Reginald Goolsby

If you made it to the bottom of the list. Save some php code and just bring everything back from the DB as you need like this:

如果你把它排到了列表的底部。保存一些 php 代码,然后根据需要从数据库中取回所有内容,如下所示:

 $items = Standard::find()->select(['name'])->indexBy('s_id')->column();