Yii Select2實時手動輸入查詢

之前在工作中遇到了問題,我要實時手動輸入篩選查詢用戶,有兩種實現方式


方式一:

<?= $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 state ...'],//直接在這個地方加入數組
    'pluginOptions' => [
        'allowClear' => true
    ],
]); ?>
這種方式只適合小範圍的數組篩選,如果這個數據超大,查詢時會出現卡頓的現象,用戶體驗非常差,建議用ajax實時查詢結果。就是下面介紹的重點:

方式二:

View.php

<?= $form->field($model, 'borrowid')->widget(kartik\select2\Select2::className(), [
    'options' => ['placeholder' => '請輸入用戶真實姓名 ...'],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 1,//重要
        'language' => [
            'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"),
        ],
        'ajax' => [
            'url' => '/borsroswer/search',
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }'),
            'cache' => true
        ],
        'width' => '400px',
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(res) { return res.text; }'),
        'templateSelection' => new JsExpression('function (res) { return res.text; }'),
    ],
]);
?>

Controller.php

public function actionSearch(){
    $q = Yii::$app->request->get('q');
    Yii::$app->response->format = Response::FORMAT_JSON;//響應數據格式爲json
    $out = ['results' => ['id' => '', 'text' => '']];
    if (!$q) {
        return $out;
    }

    $data = User::find()
        ->select('user.userId, user.realname,user.cardId,ab.status')
        ->leftJoin('account_bank ab','ab.userId=user.userId')
        ->andFilterWhere(['like', 'user.realname', $q])
        ->limit(50)
        ->asArray()
        ->all();
    $out['results'] = array_map([$this, 'format'],$data);

    return $out;
}

private function format($data){
    $result = [];
    $result['id'] = $data['userId'];
    $result['text'] = '['.$data['userId'].']['.$data['realname'].']['.$data['cardId'].']';
    return $result;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章