1. 云栖社区>
  2. PHP教程>
  3. 正文

How to make a drop down list in yii2?

作者:用户 来源:互联网 时间:2017-12-01 19:35:34

How to make a drop down list in yii2? - 摘要: 本文讲的是How to make a drop down list in yii2?, In this tutorial I would like to show you making dropdown list in yii2 using different data sources like static array d

In this tutorial I would like to show you making dropdown list in yii2 using different data sources like static array data and database table modal data.

First I would like to share basic syntax – here you go…

Yii2 DropDownList syntax – active field style echo$form->field($model,'name_field')->dropDownList( [items], [options] ); Yii2 DropDownList syntax – active form style echoHtml::field($model,'name_field')->dropDownList( [items], [options] );

Both style are almost same , but active field style is good because it maintains the creation of the form input label and help-block for error messages where active form style generate only dropdown.

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

Using below code snippet you can display the database table column’s data in the dropdownList via modal.

<?php//use yii/helpers/ArrayHelper;//use app/models/Country; // get countries from database table$countries=Country::find()->all(); // default selected country , here 10 is country id$countries->country_id=10; // convert $country modal result to array format using ArrayHelper's map() method. $countryList=ArrayHelper::map($countries,'country_id','name'); // this will generate dropdownList with given array of data.echo$form->field($model,'name')->dropDownList($countryList,['prompt'=>'Please select country']); ?>

Here we used 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 which will help to make a map ( of key-value pairs) from a multidimensional array or an array of objects.

Generating dropdownlist with option groups.

Below is the simple example on creating dropdownList with option groups

$countries=array('Asia'=>array('russia'=>'Russia','india'=>'India',),'Africa'=>array('kenya'=>'Kenya','zimbabwe'=>'Zimbabwe',),)echo$form->field($model,'country_id')->dropDownList($countries);

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。