Default DropDownList
Yii2.0 default dropdownlist syntaxt.
1 | <?php echo $form ->field( $model , 'name[]' )->dropDownList([ 'a' => 'Item A' , 'b' => 'Item B' , 'c' => 'Item C' ]); ?> |
DropDownList With Prompt Text
Yii2.0 default dropdownlist syntaxt with prompt text like default text value.
1 | <php echo $form ->field( $model , 'name[]' )->dropDownList( $listData , |
2 | [ 'prompt' => 'Select...' ]);> |
DropDownList With Model (DB) Data
Using below code, we can display the database value (via model) in dropdownlist of yii2.0 framework.
03 | $countries =Country::find()->all(); |
06 | $listData =ArrayHelper::map( $countries , 'code' , 'name' ); |
08 | echo $form ->field( $model , 'name' )->dropDownList( |
10 | [ 'prompt' => 'Select...' ]); |
Default Selection DropDownList Yii2
Using below code, we can set the default value for dropdownlist of yii2.0 framework. When we create the new entry for country population, we will try to set the value to auto select of dropDownList. During the updation it will fetch the country code automatically from db record. Please see the below code to get it.
Controller Code
03 | public function actionCreate() |
05 | $model = new Population(); |
08 | if ( $model ->load(Yii:: $app ->request->post()) && $model ->save()) { |
09 | return $this ->redirect([ 'view' , 'id' => $model ->code]); |
11 | return $this ->render( 'create' , [ |
16 | public function actionUpdate( $id ) |
18 | $model = $this ->findModel( $id ); |
19 | return $this ->render( 'update' , [ |
Create/Update Form Code
03 | use yii\widgets\ActiveForm; |
04 | use yii\helpers\ArrayHelper; |
07 | <?div class = "population-form" > |
08 | <??php $form = ActiveForm::begin(); ?> |
12 | $listData =ArrayHelper::map( $countries , 'code' , 'name' ); |
13 | echo $form ->field( $model , 'name' )->dropDownList( $listData , [ 'prompt' => 'Choose...' ]); |
16 | <??php ActiveForm:: end (); ?> |
Yii2.0 DropDownList
No comments:
Post a Comment