Yii2 dropdown empty option

Try this : You can remove the templet if you want.

<?php
  $form = ActiveForm::begin([
    'id' => 'test-form',
    'options' => ['class' => 'form-horizontal'],
    'enableClientValidation'=> true,
    'enableAjaxValidation'=> false,
    'validateOnSubmit' => true,
    'validateOnChange' => true,
    'validateOnType' => true,
    'action' => Yii::$app->homeUrl . 'your/url/path'
  ]);
?>

    echo $form->field($model, 
                'your_field_name', 
                ['template' => '<div class="col-md-3">
                                     {label}
                                </div>
                               <div class="col-md-9"> 
                                     {input}{error}{hint}
                               </div>'
                ])
                ->dropdownList($option_array, ['prompt' => '--Select--']);

<?php ActiveForm::end(); ?>

Use the following code to get the dropdownlist in yii2 friend.

<?php 
    //use app\models\Country;
    $countries=Country::find()->all();

    //use yii\helpers\ArrayHelper;
    $listData=ArrayHelper::map($countries,'code','name');

    echo $form->field($model, 'name')->dropDownList(
                                    $listData, 
                                    ['prompt'=>'Select...']);
    ?>

Why not

<?
    dropDownList($model, 
        'project', 
        $model->getProjectOptions(), 
        array('prompt'=>'Empty string')
    ); ?>
  • prompt: string, a prompt text to be displayed as the first option;

Here is old CHtml https://github.com/yiisoft/yii2/blob/master/framework/yii/helpers/base/Html.php

Can find there if you need something more.


You are looking something like this?

<?=$form->field($model, 'project')
        ->dropDownList(ArrayHelper::map(['empty'=>'Empty string'], 'id', 'value'))
        ->label(false);
?>