How to make a drop down list in yii2?

2019-01-13 03:18发布

问题:

How to make a dropdown in yii2 using an activeform and a model? Since all the methods has changed in yii2,how it is done in the new one?

回答1:

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]

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


回答2:

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


回答3:

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.

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



回答4:

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

<?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.

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


回答5:

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-']) ?>


回答6:

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

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

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


回答7:

<?= $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.



回答8:

In ActiveForm just use:

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


回答9:

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;

/* 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
        );


回答10:

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:

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


回答11:

Following can also be done. If you want to append prepend icon. This will be helpful.

<?php $form = ActiveForm::begin();    
   echo $form->field($model, 'field')->begin();
     echo Html::activeLabel($model, 'field', ["class"=>"control-label col-md-4"]); ?>
       <div class="col-md-5">
          <?php echo Html::activeDropDownList($model, 'field', $array_list, ['class'=>'form-control']); ?>
          <p><i><small>Please select field</small></i>.</p>
          <?php echo Html::error($model, 'field', ['class'=>'help-block']); ?>
       </div>
   <?php echo $form->field($model, 'field')->end(); 
ActiveForm::end();?>