yii2 kartik 小部件中的 yii2-select2 匹配器

问题描述 投票:0回答:2

我正在使用 yii2-select2 kartik 小部件来搜索城市,但是搜索城市的效果很糟糕,因为它首先在单词内部搜索,但我想先搜索后者。例如,我输入字母 K,它应该找到一个以单词 K 开头的单词,但不幸的是它首先在该单词内找到。

在基础 jquery select2 中解决了这个问题:在此处输入链接描述

但是我怎样才能将它添加到这个小部件中:在此处输入链接描述

php yii2 widget jquery-select2
2个回答
1
投票

您尝试过使用

pluginOptions
属性吗?

$match = <<< SCRIPT
function matchStart (term, text) {
    if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }
  return false;
}
SCRIPT;
echo Select2::widget([
    'name' => 'cities',
    'data' => $data,
    'options' => ['placeholder' => 'Select a city...'],
    'pluginOptions' => [
        'matcher' => new JsExpression('match'),
    ],
]);

0
投票

您可以在 matchCustom 函数中编写自己的解决方案。

这是一个完整的示例:

<?php
$script = <<< JS
    function matchCustom(params, data) {
        // If there are no search terms, return all of the data
        if (params.term.trim() === '') {
            return data;
        }

        // Do not display the item if there is no 'text' property
        if (typeof data.text === 'undefined') {
            return null;
        }


        // `params.term` should be the term that is used for searching
        // `data.text` is the text that is displayed for the data object
        const termLo = params.term.trim().toLowerCase().split(' ');
        const textLo = data.text.trim().toLowerCase();
        let allIncludes = true;
        for (let i = 0; i < termLo.length; i++) {
            if (!textLo.includes(termLo[i])){
                allIncludes = false;
                break;
            }
        }
        if (allIncludes) {
            //var modifiedData = $.extend({}, data, true);
            //modifiedData.text += ' (matched)';

            // You can return modified objects from here
            // This includes matching the `children` how you want in nested data sets
            //return modifiedData;

            return data;
        }

        // Return `null` if the term should not be displayed
        return null;
    }
JS;

$this->registerJs($script, $this::POS_HEAD);
?>

<?= $form->field($model, 'product_id')->widget(Select2::class, [
    'data' => $items,
    'options' => [
        'placeholder' => 'Select item...',
        'multiple' => false,
    ],
    'pluginOptions' => [
        'allowClear' => true,
        'matcher' => new JsExpression('matchCustom'),
        // 'minimumInputLength' => 1,
    ],
    'theme' => Select2::THEME_KRAJEE_BS3
]); ?>
© www.soinside.com 2019 - 2024. All rights reserved.