Yii2 提供兩種產生下拉選單的方式:ActiveForm::field()->dropDownList() (整合驗證、樣式) 與 Html::activeDropDownList() (輕量、完全控制屬性)。本文系統整理資料來源準備、基本用法、預設提示、模型綁定、Html 類替代方案、多維陣列分組、常見問題與最佳實踐。
use yii\helpers\ArrayHelper; use app\models\Country; $countries = Country::find()->all(); // 或 asArray()->all() $listData = ArrayHelper::map($countries, 'code', 'name'); // [ 'TW' => '台灣', 'US' => '美國' ]
value 欄位 (對應 option value)label 欄位 (對應顯示文字)<optgroup>use yii\widgets\ActiveForm;
use yii\helpers\Html;
$form = ActiveForm::begin();
// 基本用法
echo $form->field($model, 'country_code')->dropDownList($listData);
// 帶預設提示
echo $form->field($model, 'country_code')->dropDownList($listData, [
'prompt' => '請選擇國家', // 產生
'class' => 'form-control',
'id' => 'country-select'
]);
// 多維分組 (optgroup)
$grouped = ArrayHelper::map($countries, 'continent', 'code', 'name');
// $grouped = ['Asia' => ['TW'=>'台灣', 'JP'=>'日本'], 'America' => ['US'=>'美國']]
echo $form->field($model, 'country_code')->dropDownList($grouped, ['prompt' => '請選擇']);
ActiveForm::end();
id、name 屬性符合 Yii 命名規則form-control)enableAjaxValidation、enableClientValidationuse yii\helpers\Html;
echo Html::activeDropDownList($model, 'country_code', $listData, [
'prompt' => '請選擇國家',
'class' => 'custom-select',
'style' => 'width: 200px;',
'data-api' => '/country/info',
'onchange' => 'loadInfo(this.value)'
]);
// 無模型綁定的純下拉選單
echo Html::dropDownList('country', null, $listData, [
'prompt' => '請選擇',
'class' => 'form-control'
]);
data-*, on* 事件)| 需求 | ActiveForm | Html 類 | 說明 |
|---|---|---|---|
| 空白提示 (value="") | ['prompt' => '請選擇'] |
['prompt' => '請選擇'] |
最常用,表單未選時提交空字串 |
| 預設選中特定值 | 模型屬性預設值 $model->country_code = 'TW' |
選項陣列鍵值對應即自動選中 | 控制器 actionCreate 給模型預設值 |
| 不可選的分隔標題 | 多維陣列 ArrayHelper::map(..., 'group') |
同左 | 產生 <optgroup label="..."> |
| Placeholder (輸入框風格) | 不支援 (select 無 placeholder) | 不支援 | 需用 JS 庫 (Select2, Choices.js) 模擬 |
public function actionCreate() {
$model = new UserForm();
$model->country_code = 'TW'; // 預設值
$countries = Country::find()->asArray()->all();
$listData = ArrayHelper::map($countries, 'code', 'name');
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// 儲存邏輯
}
return $this->render('create', [
'model' => $model,
'listData' => $listData,
]);
}
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$form = ActiveForm::begin();
?>
<?= $form->field($model, 'username')->textInput() ?>
<?= $form->field($model, 'country_code')->dropDownList($listData, [
'prompt' => '請選擇國家',
'class' => 'form-control'
]) ?>
<?= Html::submitButton('送出', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
$listData 為空、鍵名錯誤 (如用 'id' 但模型存 'code')field() 第二參數不符、$listData 鍵值型別不符 (字串 vs 整數)rules() 缺少該欄位規則、ActiveForm 未正確 begin()/end()ArrayHelper::map 第四參數欄位名錯誤、資料未正確分組ActiveForm::field()->dropDownList(),享受框架整合優勢。ArrayHelper::map() 轉換,保持控制器/視圖分離。'prompt' => '請選擇...',提升 UX 並利驗證。Html::encode() (ArrayHelper::map 自動處理 ActiveRecord 屬性),防 XSS。相關專題:《Yii 框架入門及常用技巧總結》、《PHP 優秀開發框架總結》。