原生 <select> 在選項超過 20 條時體驗極差。Yii2 生態首選 kartik-v/yii2-widget-select2,封裝 jQuery Select2 4.x,支援本地搜索、AJAX 遠程加載、多選標籤、模板自定義等企業級功能。
composer require kartik-v/yii2-widget-select2 "*"
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
<?= $form->field($model, 'companies_company_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Companies::find()->all(), 'company_id', 'company_name'),
'language' => 'en',
'options' => ['placeholder' => 'Select a company ...', 'multiple' => false],
'pluginOptions' => [
'allowClear' => true, // 顯示清除按鈕
'minimumInputLength' => 1, // 輸入 1 字符開始搜索
],
]) ?>
<?= $form->field($model, 'user_id')->widget(Select2::classname(), [
'options' => ['placeholder' => '搜索用戶...', 'multiple' => true],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 2,
'ajax' => [
'url' => \yii\helpers\Url::to(['user/search']),
'dataType' => 'json',
'data' => new \yii\web\JsExpression('function(params) { return {q: params.term, page: params.page}; }'),
'processResults' => new \yii\web\JsExpression('function(data) { return {results: data.items, pagination: {more: data.more}}; }'),
],
'templateResult' => new \yii\web\JsExpression('function(item) { return item.text; }'),
'templateSelection' => new \yii\web\JsExpression('function(item) { return item.text; }'),
],
]) ?>
控制器 actionSearch 返回格式:
return Json::encode([
'items' => array_map(function($u){ return ['id'=>$u->id, 'text'=>$u->username]; }, $users),
'more' => count($users) >= 20,
]);
| 選項 | 說明 |
|---|---|
| allowClear | 可清除選擇 |
| multiple | 多選模式(標籤顯示) |
| tags | 允許創建新標籤(配合 createTag) |
| maximumSelectionLength | 限制最多選幾項 |
| minimumInputLength | 觸發搜索最少字符數 |
| dropdownAutoWidth | 下拉框自適應寬度 |
| theme | 主題:default, bootstrap, classic |
| language | 語言包(需對應文件) |
| placeholder | 佔位符(也可在 options 中設定) |
| escapeMarkup | 關閉 HTML 轉義(自定義模板時需設為 false) |
https://demos.krajee.com/widget-details/select2 — 含單選、多選、AJAX、標籤、模板、主題等 20+ 實例。
Select2 + Yii2 = 企業級下拉選擇體驗。記住:**大數據必須走 AJAX**,前端只渲染可見選項,後端分頁返回,前後端分工明確才能支撐萬級選項無卡頓。