yii2 中的 dropDownList 自动完成

dropDownList Autocomplete in yii2

在 Yii2 中,我希望我的多选字段之一在用户开始输入时自动完成。我已经加载了所有产品,但它们超过 1000 个,加载速度非常非常慢。所以我需要一个下拉列表,它允许我输入一些产品的标题,然后它会建议我一个选项列表。

 <?php
     $cats = Product::find()->where('active = 1')->all();
     $prArr = array();
     if ($cats) {
       foreach ($cats as $cat) {
          $prArr[$cat->id] = $cat->title;
       }
     }
     $selectedProducts = '';
     if (isset($_POST['RelProducts']) and ! empty($_POST['RelProducts'])) {
         $selectedProducts = array();
         foreach ($_POST['RelProducts'] as $cat) {
               $selectedProducts[$cat] = $cat;
         }
     }
     ?>
     <?= Html::dropDownList('RelProducts[]', $selectedProducts, $prArr, ['multiple' => 'multiple', 'style' => 'width:300px;', 'rows' => 10, 'id' => 'relProductSelect']); ?>

这是脚本:

$('#relProductSelect').multiSelect({
    selectableHeader: "<a href='#' id='select-all-rel-prod'>Избери всички</a><br /><input type='text' class='search-input' autocomplete='off' placeholder='търси...' style=\"width:100%;margin-bottom:5px;\">",
    selectionHeader: "<a href='#' id='deselect-all-rel-prod'>Премахни всички</a><br /><input type='text' class='search-input' autocomplete='off' placeholder='търси...' style=\"width:100%;margin-bottom:5px;\">",
    afterInit: function (ms) {
        var that = this,
                $selectableSearch = that.$selectableUl.prev(),
                $selectionSearch = that.$selectionUl.prev(),
                selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
                selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';

        that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
                .on('keydown', function (e) {
                    if (e.which === 40) {
                        that.$selectableUl.focus();
                        return false;
                    }
                });

        that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
                .on('keydown', function (e) {
                    if (e.which == 40) {
                        that.$selectionUl.focus();
                        return false;
                    }
                });
    },
    afterSelect: function () {
        this.qs1.cache();
        this.qs2.cache();
    },
    afterDeselect: function () {
        this.qs1.cache();
        this.qs2.cache();
    }
});

如何加急请求?

嗯,需要最少努力的解决方案之一可能是使用选项

minimumInputLength: Minimum number of characters required to start a search.

只有当搜索词达到一定长度时才开始过滤结果效率更高。在您的情况下,它可以产生不同。

根据您的评论,您正在使用 KartikSelect2-multiselect,但您没有为其添加源代码,而 js 代码用于 jquery muti-select,但我会为您提供 server-side 实现

的代码
Select2::widget([
    'name' => 'my-dropdown',
    'data' => $data,
    'options' => ['placeholder' => 'Select a product ...', 'multiple' => true],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength':3
    ],
])

您可以根据需要调整输入值。 希望对你有帮助。