1. 程式人生 > >Yii2 使用select2 元件實現下拉搜尋

Yii2 使用select2 元件實現下拉搜尋

剛開始使用yii,需要實現下拉多選搜尋,就找到了select2這個元件,先看看實現後的效果:

這裡寫圖片描述

如何安裝select2網上有很詳細的教程,這裡不做贅述。

完成後只需要在檢視檔案use kartik\select2\Select2就可以了。
具體的檢視中的程式碼如下:

<?=
    $form->field($model, 'search')->widget(Select2::classname(), [
        'options' => ['placeholder' => '請輸入使用者ID ...'],
        'pluginOptions'
=> [ 'id' => new JsExpression("function(rs) { return rs.taskId; }"), 'placeholder' => 'search ...', 'multiple' => true, 'allowClear' => true, 'language' => [ 'errorLoading' => new
JsExpression("function () { return 'Waiting...'; }"), ], 'ajax' => [ 'url' => Url::to(['gm-account-info/search-title']), '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; }'), ], ]); ?>

控制器中程式碼如下:

$out = ['results' => ['userid' => '', 'text' => '']];
        if (!$q) {
            echo json_encode($out);die;
        }
        $data = GmAccountInfo::find()
            ->select('uid as userid, account_name as text')
            ->andFilterWhere(['like', 'uid', $q])
            ->asArray()
            ->all();

        $out['results'] = array_values($data);
        echo json_encode($out);die;

這樣出來的結果是這樣的:

這裡寫圖片描述

搜尋結果是下拉顯示出來了,但是無法選中。
這裡寫圖片描述

最後將控制器中的程式碼做了一點修改:

 $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            echo json_encode($out);die;
        }
        $data = GmAccountInfo::find()
            ->select('uid as id, uid as text')   //userid=>id
            ->andFilterWhere(['like', 'uid', $q])
            ->asArray()
            ->all();

        $out['results'] = array_values($data);
        echo json_encode($out);die;

將返回資料的格式調整為[‘id’=>”,’text’=>],就正常了。

結論:使用select2 元件時,後端返回的資料格式必須是[‘id’=>”,’text’=>]這個格式的。