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?
-
Is this question edited. If yes what was the initial question. – Kshitiz May 28 '14 at 05:43
-
@Dency G B I am looking for answers to my another question similar to this.. Is it possible for you to have a look at it?? [Link here](http://stackoverflow.com/questions/39511933/yii2-move-deleted-data-from-one-table-to-another-table) – Mohan Prasad Sep 16 '16 at 08:40
13 Answers
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) ?>

- 8,096
- 9
- 47
- 78
-
1Reminder that Yii2 makes use of namespaces, hence the 'use namespaces' in the solution. Took me a while to think what they were for. – johnsnails Jun 05 '14 at 05:46
-
11Please don't directly follow this example and have data fetching/building logic in your views! – AndrewPK Mar 11 '15 at 01:54
-
@AndrewPK: could you provide an example of how you'd prefer this done? Passed through from the controller presumably? – almcnicoll Apr 17 '15 at 00:10
-
@AndrewPK why? it's like widgets, you can fetch data in you views and it isn't anti-pattern. But you cannot create queries that create something in db and so on – Auine Jan 24 '16 at 10:45
-
4@Auine did you create your own pattern? mvc, mvvm, etc., all describe a separation of concerns. a view should only ever be concerned with displaying data it was given - it should not be performing queries, GETs, etc. If you don't want to adhere to one of those patterns, that's cool too - but it makes things more difficult when you need to swap out views to support different platforms in the future. The edited answer the author provided above is a more ideal solution in MVC - having the find() in the controller and passing the data to the view render. – AndrewPK Jan 26 '16 at 19:43
-
@Auine putting queries in views or widgets is bad practice. It leads to a poor scaling of db load. Often if views are reused across the platform dev's will lose track of the number of queries are being conducted for a specific page load. As a result a query that needs only run once can be run many more times unnecessarily. Especially if a widget appears more than once in a given view. This is not considered "DRY", https://en.wikipedia.org/wiki/Don%27t_repeat_yourself – BajaBob Apr 21 '16 at 18:44
-
@BajaBob, so when you use some widget in the VIEW with some data from DB, how do you get the data? – Auine May 05 '16 at 11:29
-
@Auine, queries are handled in the controller and sent to the view through the `render` method. That way if you have several widgets or views that require the same data less queries are run as a result. Ultimately by following this convention you can easily discover in your controller if you can consolidate queries. For example, if two queries can be combined into one you will improve loading performance. – BajaBob May 05 '16 at 16:31
-
@BajaBob For several years I used to think (and code) dogmatically like you. But working with Craft CMS (based on Yii) has since shown me that *sometimes* queries are more cleanly done from within a view. Example: If you have a widget displaying upcoming events and that widget needs to be shown in multiple areas of your site (homepage, news area, events area etc.). Instead of having to run that query in each controller, it's just coded once inside that view. If you stop displaying the widget in an area the query gets automatically suppressed, whereas it can often be forgotten about otherwise. – Simon East Apr 26 '17 at 06:10
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();
?>

- 9,857
- 2
- 39
- 50
-
@DencyGB the simplest and I think the only solution would be to give the first select field name and manipulate `.on('change')` event in jquery to populate second field based on selection of first. – Arman P. Feb 07 '14 at 01:01
-
I want remove ordinary number from list that automatically shows. – Mohammad Aghayari Jun 14 '16 at 21:04
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

- 1,971
- 20
- 29
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']);
?>

- 3,850
- 1
- 23
- 26
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-']) ?>

- 12,262
- 10
- 69
- 70
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(); ?>

- 993
- 9
- 28
-
Its says undefined variable items when accessing view. I used this way added code to controller `$this->view->params['items'] = $items;` and in my view page `field($model, 'plan_type', ['options' => ['class' => ' input select']])->dropdownList( $this->params['items'],['prompt'=>'Select Plan','class' => 'selectpicker', 'data-live-search' => 'true','label'=>false]);?>` – RN Kushwaha Oct 11 '15 at 13:08
-
<?= $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.

- 3,535
- 3
- 25
- 33

- 986
- 3
- 14
- 25
-
1On top of the view file, one needs to write `use yii\helpers\ArrayHelper;` to be able to use the helper. – Gogol Jul 08 '15 at 13:58
In ActiveForm
just use:
<?=
$form->field($model, 'state_id')
->dropDownList(['prompt' => '---- Select State ----'])
->label('State')
?>

- 10,639
- 3
- 49
- 62

- 71
- 1
- 2
- 4
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
);

- 3,843
- 1
- 23
- 38
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();

- 635
- 8
- 10
Html::activeDropDownList($model, 'id', ArrayHelper::map(AttendanceLabel::find()->all(), 'id', 'label_name'), ['prompt'=>'Attendance Status'] );

- 11
- 2
<?=$form->field($model, 'category_id')->dropdownList(
\common\models\Category::find()
->select(['name', 'id'])
->indexBy('id')
->column(),
['prompt'=>'select category']
)?>
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();?>

- 2,673
- 1
- 18
- 24