新手,不擅長寫js,純粹只是分享一下本身遇到的問題供你們參考一下php
select2這個插件,就是帶搜索功能的下拉選擇框
效果如圖:web
使用前先肯定本身的項目安裝了select2,若是沒有的話就用composer安裝一下ajax
use kartik\select2\Select2;
$data = [2 => 'widget', 3 => 'dropDownList', 4 => 'yii2']; $form->field($model, 'title')->widget(Select2::classname(), [ 'data' => $data, 'options' => ['placeholder' => '請選擇 ...'], ]);
Select2::widget([ 'name' => 'title', 'data' => $data, 'options' => ['placeholder' => '請選擇...'] ]);
Select2::widget([ 'name' => 'title', 'value' => 2, 'data' => $data, 'options' => ['placeholder' => '請選擇...'] ]);
Select2::widget([ 'name' => 'title', 'value' => 2, 'data' => $data, 'options' => ['multiple' => true, 'placeholder' => '請選擇...'] ]);
$form->field($model, 'back_reason')->widget(Select2::classname(), [ 'name' => 'search', 'value' => isset($params['company_id'])?$params['company_id']:'', 'data' => \yii\helpers\ArrayHelper::map(\app\models\BackReason::find()->where(['level'=>\app\models\BackReason::LEVEL_2])->asArray()->all(),'id','reason'), 'options' => ['placeholder' => '退稿緣由搜索','style'=>'width:110px;','id'=>'searchreason',], 'pluginOptions' => [ 'allowClear' => true, 'width' => '220px', ], ])
<script> $(function() { $.fn.modal.Constructor.prototype.enforceFocus = function () {}; }); </script>
use kartik\select2\Select2; use yii\web\JsExpression; <? php echo $form->field($model, 'title')->widget(Select2::classname(), [ 'options' => ['placeholder' => '請輸入標題名稱 ...'], 'pluginOptions' => [ 'placeholder' => 'search ...', 'allowClear' => true, 'language' => [ 'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"), ], 'ajax' => [ 'url' => '這裏是提供數據源的接口', 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }') ], 'escapeMarkup' => new JsExpression('function (markup) { return markup; }'), 'templateResult' => new JsExpression('function(res) { return res.text; }'), 'templateSelection' => new JsExpression('function (res) { return res.text; }'), ], ]); ? >
public function actionSearchTitle ($q) { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $out = ['results' => ['id' => '', 'text' => '']]; if (!$q) { return $out; } $data = Article::find() ->select('id, title as text') ->andFilterWhere(['like', 'title', $q]) ->limit(50) ->asArray() ->all(); $out['results'] = array_values($data); return $out; }